简体   繁体   English

printf在gcc错误的结果

[英]printf in gcc wrong result

Case 1: printf("%f",(7/2)); 案例1: printf("%f",(7/2)); in gcc output is 0.000000. 在gcc输出中是0.000000。

Case 2: float k= 7/2; 案例2: float k= 7/2; printf("%f",k); in gcc output is 3.000000. 在gcc输出是3.000000。

In the first case printf expects float but gets Integer so gives wrong result. 在第一种情况下,printf需要浮点但得到Integer所以给出了错误的结果。 But in second case it does type conversion. 但在第二种情况下,它进行类型转换。

Here are my questions- 这是我的问题 -

  1. Why does not gcc give type mismatch error/ warning in the first case? 为什么gcc在第一种情况下不会出现类型不匹配错误/警告?
  2. In 2nd case it is doing type conversion by default but why not in 1st case? 在第二种情况下,它默认进行类型转换,但为什么不在第一种情况下呢?

In 2nd case it is doing type conversion by default but why not in 1st case? 在第二种情况下,它默认进行类型转换,但为什么不在第一种情况下呢?

In first case 7 and 2 both are of int type. 在第一种情况下, 72都是int类型。 Dividing 7 by 2 will give you an int . 7除以2会得到一个int Printing it with %f will invoke undefined behavior . 使用%f打印它将调用未定义的行为 You will get anything. 你会得到任何东西。 In this case there is no type conversion. 在这种情况下,没有类型转换。

Try this 尝试这个

printf("f", (7.0/2));  

In second case k is of float type hence the result of 7/2 is converted to the type of k by default. 在第二种情况下, kfloat型,因此7/2的结果默认转换为k的类型。

Why does not gcc give type mismatch error/ warning in the first case? 为什么gcc在第一种情况下不会出现类型不匹配错误/警告?

Compiling the first statement with -Wall flag is giving the warning: 使用-Wall标志编译第一个语句会发出警告:

[Warning] format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]

1) gcc does not by default check types in format string with arguments - so it "interpretes" the data (ie. the integer) as float at runtime 1)gcc默认情况下不会使用参数检查格式字符串中的类型 - 因此它在运行时将数据(即整数)“解释”为float

2) gcc now interpretes the float as float at runtime . 2)gcc现在在运行时将float解释为float。

GCC can give a warning, but you didn't enable it. 海湾合作委员会可以发出警告,但你没有启用它。 Try compile with flag -Wall , you would see: 尝试用标志-Wall编译,你会看到:

warning: double format, different type arg (arg 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM