简单课后习题求助C
华氏度和摄氏度转换:1. #include <stdio.h>
2.
3. int main()
4. {
5. int fah;
float cel;
6.
7. printf("请输入华氏度:");
8. scanf("%d", &fah);
9.
10. cel = (fah - 32) * 5 / 9;
11. printf("转换为摄氏度是:%.2f\n", cel);
12.
13. return 0;
14. }
fah =
输出 cel = 7.22
问题:请问下我如果是float fah cel;输出cel = 7.22. 但是如果我是int fah;输出 cel = 7.00.请问这是为什么呢? 1.精度问题。
2.你输出问题。
参考:
https://blog.csdn.net/qq_44101151/article/details/86551372
你是代码编写者,所以你确定精度后 float 你才 %.2f,你确定是int 才%d。
int精度你用%.2f当然也可以。7.00 == 7 ba21 发表于 2019-11-16 22:44
1.精度问题。
2.你输出问题。
不好意思我还是没有很懂。。因为cel我这里是确定为 float类型,但是我int fah和float fah会有什么区别吗?因为我fah 的输入是45,但是 我int fah的话 cel = 7 float fah的话 cel= 7.22. 但是这两种情况的cel 都是float类型呀,为什么会这么变化呢? 当fah为int型时, cel = (fah - 32) * 5 / 9,结果本应该是7.2222,但是因为fah是int型,计算机自动转换为四舍五入后的值,因为这个赋值是先计算 等号右边的,计算完再赋值
参考:https://zhidao.baidu.com/question/496756578.html?sort=11&rn=5&pn=0#wgt-answers int类型除法会自动取整,所以你这个cel其实是将一个int类型强制转换成了float(其实是double)类型,然后再输出出来,就是cel=**右边的算出来应该是7,赋值运算后强制换成7.000000,之后你只要两位小数,所以就会变成这个亚子。
页:
[1]