简体   繁体   English

If-Else语句不打印结果

[英]If-Else statement not printing results

I am trying to plug in negative values, positive values, and zero into this program, and although I do get a printed result for the first two, whenever I type 0 , I get no response. 我正在尝试将负值,正值和零插入此程序,尽管我确实得到前两个的打印结果,但是无论何时键入0 ,都没有响应。 The command prompt simply ends the program. 命令提示符只是结束程序。

#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;   
}

Maybe try 也许尝试

    if ( n > 0 ) {
       //...
    } else {
       if ( n < 0 ) {
          //...
       } else {
          //...
       }
    }

EDIT: You can always return from main earlier: 编辑:您总是可以从主要更早return

    if ( n > 0 ) {
       //...
       return 0;
    } else if ( n < 0 ) {
       //...
       return 0;
    }
    // program reaches this line only when n == 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM