添加分数S = 1/2 +(1 * 3)/(2 * 4)+(1 * 3 * 5)/(2 * 4 * 6)+ ... +(1 * 3 * 5 * ...(2 * n-1))/(2 * 4 * 6 * ... 2 * n)) 该练习从用户输入中获取n的值,但在此示例中,我将其初始化为5。
#include <stdio.h>
int main() {
int numerator=1, denominator=1, k, n=5;
float S=0;
for (k=1; k<=n; k++) {
numerator *= (2*k - 1);
denominator *= 2*k;
S += numerator/denominator; //this does not work and I can't tell why
printf("numerator= %d\n", numerator);
printf("denominator= %d\n", denominator);
printf("S= %f\n", S);
}
printf("S= %f\n", S); // this should print 1.70703125 but it prints 0.000000
scanf_s("%d", &n);
return 0;
}
答案 0 :(得分:0)
除法numerator/denominator
是一个整数除法。结果是一个整数,所有小数都被截断(截断)。
除法中的至少一部分必须为浮点值,而整个表达式为浮点。与(float)numerator/denominator
中一样。