简体   繁体   中英

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.

It should be if(b>=97 && b<=122) instead, which limits b in the range of lowercase.

Personally I prefer to write as if (97 <= b && b <= 122) which makes it easy to see its range.

Do you think this would be easier if you use the library <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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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