學點 C 語言(17): 資料類型 – 因類型引發的問題或錯誤

來源:互聯網
上載者:User
1. 運算結果超出類型大小:
#include <stdio.h>#include <limits.h>int main(void){    short s1 = SHRT_MAX;    short s2 = SHRT_MAX;    short num1;    int num2;    /* 不會是期望的值 */    num1 = s1 + s2;    printf("%d\n", num1);    /* 這樣可以了 */    num2 = s1 + s2;    printf("%d\n", num2);      getchar();    return 0;}

2. 把大的賦給小的:

#include <stdio.h>#include <limits.h>int main(void){    unsigned int   n1 = INT_MAX;    unsigned char  n2;    unsigned short n3;    n2 = n1;    n3 = n1;    printf("%u, %u, %u\n", n1, n2, n3);    printf("%#X, %#X, %#X\n\n", n1, n2, n3);    n1 = LLONG_MAX;    printf("%lld, %u\n", LLONG_MAX, n1);    printf("%#llx, %#x\n", LLONG_MAX, n1);      getchar();    return 0;}

3. 把浮點數賦給整數:

#include <stdio.h>int main(void){    double pi = 3.14159265;    int i;    /* 只會留下整數部分 */    i = pi;    printf("%d\n", i);    /* 並且不會四捨五入 */    i = 3.6;    printf("%d\n", i);          getchar();    return 0;}

4. 兩個整數相除只返回整數:

#include <stdio.h>int main(void){    int n1 = 3;    int n2 = 2;    float f;    /* 這樣不行; 但如果你本來就只想要整數部分, 那不正中下懷嗎? */    f = 3 / 2;    printf("%g\n", f);    /* 這樣才可以(如果只有兩個運算數, 其中一個是浮點數即可, 但多了不行) */    f = 3.0 / 2.0;    printf("%g\n", f);    /* 這樣不行 */    f = n1 / n2;    printf("%g\n", f);    /* 這樣也不行 */    f = (float)(n1 / n2);    printf("%g\n", f);    /* 這樣才可以 */    f = (float)(n1) / (float)(n2);    printf("%g\n", f);            getchar();    return 0;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.