This question already has answers here:
C program to convert Fahrenheit to Celsius always prints zero

(7个答案)



Why does division result in zero instead of a decimal?

(5个答案)


2年前关闭。




我正在尝试计算p1=(1/1)*(1/2)*...*(1/n),但是出了点问题,而printf给了我0.000...0
#include <stdio.h>

int main(void) {

    int i,num;
    float p3;

    do {
        printf ("give number N>3 : \n" );
        scanf( "%d", &num );
    } while( num <= 3 );

    i = 1;
    p3 = 1;

    do {
        p3=p3*(1/i);
        printf( "%f\n",p3 );
    } while ( i <= num );

    printf("\nP3=%f",p3);
    return 0;
}

最佳答案

(1/i)
iint,所以是整数除法,如果是i > 1,则结果为0。使用1.0/i进行浮点除法。

关于c - 除以1/n总是返回0.0 ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13331054/

10-09 01:05