繁体   English   中英

在C中,为什么程序没有重新协调第二个if语句或大写char变量?

[英]in C why the program is not reconizing the second if statement or upper case char variable?

编写一个程序,询问用户角度(以度为单位)。 然后,要求用户键入字母。 如果用户键入小写字母,则将角度的正弦显示为小数点后四位。 如果用户键入大写字母,则将角度的余弦显示到小数点后四位。

所以这就是我到目前为止所拥有的,为什么程序无法识别大写并打印余弦?

#include<stdio.h>
#include<math.h>

#define PI 3.14159265

main()
{
    int a;
    double x,y;
    char b;

    printf("What is the angle in degrees?\n");
    scanf("%i",&a);
    printf("Type a letter!\n");
    scanf("%i",&b);
    x=sin(a*PI/180);
    y=cos(a*PI/180);

    if (b>=97 | b<=122)
    {
        printf("The sine of %i is %.4f.\n",a,x);
    }
    if (b>=65 && b<=90) 
    {
        printf("The cosine of %i is %.4f.\n",a,y);
    }

    return 0;
}

因为if(b>= 97 | b <= 122)将始终为true。

应该是if(b>=97 && b<=122) ,它将b限制在小写字母的范围内。

就我个人而言,我更喜欢将其写为if (97 <= b && b <= 122) ,这样很容易看到其范围。

您是否认为使用库<ctype.h>会更容易?

#include <stdio.h>
#include <ctype.h>
#include <math.h>

#define PI 3.14159265

int main()

{
    int a;
    double x,y;
    char b;

    printf("What is the angle in degrees?\n");
    scanf("%d", &a);
    printf("Type a letter!\n");
    scanf(" %c", &b);

    x=sin(a*PI/180);
    y=cos(a*PI/180);

    if (isupper(b))
    {
        printf("The sine of %d is %.4f.\n",a,x);
    }
    else
    {
        printf("The cosine of %d is %.4f.\n",a,y);
    }

    return 0;
}

暂无
暂无

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

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