为什么1/2=0?

C primer plus 课后作业 3.11.8

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main(void)
{
int cup; //1cup=0.5pint=8ounce=16big=48small
printf("How many cups?\n");
scanf("%d",&cup);
printf("%d Cup is %f in pint,%d in ounce,%d in big and %d in small",cup, cup/2, cup*8, cup*16, cup*48);
}
//output: 1 Cup is 0 in pint,8 in ouns,16 in big and 48 in small
//cup/2改成cup*0.5
//output: 1 Cup is 0.500000 in pint,8 in ounce,16 in big and 48 in small

查阅发现
C 的除法,当两边都是整型值时,做整数除法,得到的也是整数,并会对形如5/3的运算结果做截断处理,并且不四舍五入

如果两边至少有一个为 float 或者 double,那么将做浮点数除法,1.0/2=0.5 。

C 并不推荐这种混合类型的除法运算,因为计算机原理上无法做到浮点数除以整数的运算。用浮点数除以整数时,C 编译器只是将整数转换为了浮点数

1
2
3
    float c=2.0;
printf("%f",cup/c);
//output : 0.500000
Author

BakaFT

Posted on

2020-02-26

Updated on

2023-12-28

Licensed under

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×