我正在尝试将负值,正值和零插入到此程序中,虽然我确实得到前两个的打印结果,但每当我键入0
时,我都没有得到回复。命令提示符只是结束程序。
#include<stdio.h>
#include<math.h>
int main(void)
{
int n, b;
float add;
int frac;
float sum=0.0;
printf("Enter n(1): "); scanf("%d", &n);
if(n>0)
{
for(add = 0; add <= n; add ++)
{
sum += add;
}
printf("The sum of integers from 1 to %d is %f\n", n, sum);
}
else if(n < 0)
{
b=abs(n);
for(frac = 1; frac <= b; frac ++)
{
sum += (1.0f)/(float)frac;
}
printf("The sum of integers from 1 to 1/%d is %f\n", b, sum);
}
else
{
printf("For n = 0, the sum is 0.0\n");
}
return 0;
}
答案 0 :(得分:-2)
也许试试
if ( n > 0 ) {
//...
} else {
if ( n < 0 ) {
//...
} else {
//...
}
}
编辑:您可以随时从{main} return
获得。{/ p>
if ( n > 0 ) {
//...
return 0;
} else if ( n < 0 ) {
//...
return 0;
}
// program reaches this line only when n == 0