#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节规定:
如果任何参数不是相应转换规范的正确类型,则行为未定义。

09-25 16:48
查看更多