简体   繁体   English

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

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

Write a program that asks the user for an angle (in degrees). 编写一个程序,询问用户角度(以度为单位)。 Then, ask the user to type a letter. 然后,要求用户键入字母。 If the user types a lower case letter, display the sine of the angle to four decimal places. 如果用户键入小写字母,则将角度的正弦显示为小数点后四位。 If the user types an upper case letter, display the cosine of the angle to four decimal places. 如果用户键入大写字母,则将角度的余弦显示到小数点后四位。

So this is what i have so far, why will the program not recognize the upper case and print the cosine? 所以这就是我到目前为止所拥有的,为什么程序无法识别大写并打印余弦?

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

Because if(b>= 97 | b <= 122) will always be true. 因为if(b>= 97 | b <= 122)将始终为true。

It should be if(b>=97 && b<=122) instead, which limits b in the range of lowercase. 应该是if(b>=97 && b<=122) ,它将b限制在小写字母的范围内。

Personally I prefer to write as if (97 <= b && b <= 122) which makes it easy to see its range. 就我个人而言,我更喜欢将其写为if (97 <= b && b <= 122) ,这样很容易看到其范围。

Do you think this would be easier if you use the library <ctype.h> ? 您是否认为使用库<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