質問

I just started learning C, and I learnt that the / sign is the division operator. I was experimenting, and was wondering why 5/7 printf the number 0.

Here is my program:

#include<stdio.h>

main()
{
    int n;
    n = 5/7;
    printf("%d", n);
}

Thank you!

役に立ちましたか?

解決

This is because of integer division. 5/7 makes 0.71.., and the integer part of this number is 0, hence it prints 0. To solve this problem use float type (or double type) variables as well as constants for example try:

float f = 5.0 / 7.0;

print variable f with format string %f

他のヒント

Because it is 0.

5/7 is an integer division, because both 5 and 7 are integers. The result of the integer division 5/7 is 0.

n, the variable which you assign the result to, is also an int.

You'd have floating point division if you wrote 5.0/7.0. However, since you assign the result to n which is, again, an int, its value would be also 0. Of course, if you assign the result of 5.0/7.0 to a double variable, you get decimals in it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top