Вопрос

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