简体   繁体   English

int和float除以0为输出

[英]int and float division giving 0 as output

int main(void)
{
  int x;
  float y;

  x=10;
  y=4.0;

  printf("%d\n",x/y);

  return 0;
}

I compiled this code using a gcc compiler and when run I get 0 as output. 我使用gcc编译器编译了这段代码,运行时我得到0作为输出。
Why is this code giving output as 0 instead of 2? 为什么此代码将输出设为0而不是2?

IT's not the division, it's the print format. 它不是分部,而是打印格式。

Change: 更改:

printf("%d\n",x/y);

to: 至:

printf("%f\n",x/y);

The result of x/y is a float and is transferred to printf() as such. x / y的结果是一个float ,并且这样转移到printf()
However, you told printf() using %d to assume the input is an int . 但是,您使用%d告诉printf()假设输入是int
There is no type-checking or automatic type-conversion in this case. 在这种情况下,没有类型检查或自动类型转换。 printf() will just execute what you asked. printf()只会执行你提出的问题。 This, by sheer accident, results in a 0 being printed. 由于纯粹的意外,这导致打印0

You should have specified %d in the format string and cast the result of the division to int . 您应该在格式字符串中指定%d并将除法的结果强制转换为int

printf("%d\n", (int)(x/y) );

Or you could have used %f , but then you would have gotten 2.5 as output. 或者您可以使用%f ,但那么您将获得2.5作为输出。 (You might want to take a look at the floor() function too.) (你可能也想看看floor()函数。)

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

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