gpt4 book ai didi

C 相同输出不同结果

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:40 26 4
gpt4 key购买 nike

#include<stdio.h>

int main(void) {

int m=2, a=5, b=4;
float c=3.0, d=4.0;

printf("%.2f,%.2f\n", (a/b)*m, (a/d)*m);
printf("%.2f,%.2f\n", (a/d)*m, (a/b)*m);

return 0;
}

结果是:

2.50,0.00
2.50,-5487459522906928958771870404376799406808566324353377030104786519743796498661129086808599726405487030183023928761546165866809436788166721199470577627133198744209879004896284033606071946689658593354711574682628407789000148729336462084532657713450945423953627239707603534923756075420253339949731915621203968.00

我想知道造成这种差异的原因。

但是,如果我将 int 更改为 float,答案与我预期的一样。

结果是:

2.50,2.50
2.50,2.50

最佳答案

您使用了错误的格式说明符,试试这个:

#include<stdio.h>

int main(void)
{
int m=2,a=5,b=4;
float fm=2,fa=5,fb=4;
float c=3.0,d=4.0;

//First expression in this printf is int and second is float due to d
printf("%d , %.2f\n\n",(a/b)*m,(a/d)*m);

//Second expression in this printf is int and first is float due to d
printf("%.2f , %d\n\n",(a/d)*m,(a/b)*m);

printf("%.2f , %.2f\n\n",(fa/b)*fm,(fa/d)*fm);
printf("%.2f , %.2f\n\n",(fa/d)*fm,(fa/b)*fm);
return 0;
}

输出:

2 , 0

0 , 1074003968

2.50 , 2.50

2.50 , 2.50

C99 标准第 7.19.6.1 p9 节说:

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

关于C 相同输出不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28081048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com