编写一个程序,询问用户角度(以度为单位)。然后,请用户键入一封信。如果用户键入小写字母,则将角度的正弦值显示为小数点后四位。如果用户键入大写字母,则将角度的余弦显示为小数点后四位。
到目前为止,这就是我所拥有的,为什么程序不能识别大写并打印余弦?
#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;
}