#include <stdio.h>
#define PI 3.141593
int main (void)
{
    float out, outrad, outarea, in, inrad, inarea, final;
    printf("Enter outer diameter: ");
    scanf("%f", &out);
    outrad = out/2;
    outarea = PI * (outrad * outrad);

    printf("Enter inner diameter: ");
    scanf("%f", &in);
    inrad = in/2;
    inarea = PI * (inrad * inrad);
    final = outarea - inarea;

    //if ( out < in)
    //{
    //    printf("Invald inputs: Inner diameter must be less than outer diameter\n");
    //}
    if ( out < 0 && in < 0)
    {
        printf("Invalid inputs: Both diameters must be positive.\n");
    }
    else if ( out < in )
    {
        printf("invalid inputs: Inner diameter must be less than outer diameter\n");
    }
    else {
        printf("Surface area: %0.6f\n", final);
    }

    return 0;
}


该程序可以编译并正常工作,除非如果我的输入小于0,则不执行第一个IF语句。无论如何,它只会继续计算表面积。我是否缺少某些语法?

Run 1
Enter outer diameter: 13.5
Enter inner diameter: 0
Surface area: 143.138824
Run2
Enter outer diameter: 5
Enter inner diameter: 4
Surface area: 7.068584
Run3
Enter outer diameter: 4
Enter inner diameter: 5
invalid inputs: Inner diameter must be less than outer diameter
Run4
Enter outer diameter: 4
Enter inner diameter: 0
Surface area: 12.566372
Run5
Enter outer diameter: 0
Enter inner diameter: 0
Surface area: 0.000000

最佳答案

&&替换为||

基本上,如果in OR out小于零,则要运行它。
如果两者均小于零,则应该运行,因为进和出小于零。

关于c - IF语句在C中被忽略,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49725452/

10-13 23:12