编写一个程序,询问用户角度(以度为单位)。然后,要求用户键入一个字母。如果用户键入小写字母,则将角度的正弦值显示为四位小数。如果用户键入大写字母,则将角度的余弦值显示为四位小数。
所以这就是我到目前为止,为什么程序不能识别大写并打印余弦?
#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;
}
答案 0 :(得分:2)
因为if(b>= 97 | b <= 122)
永远是真的。
应该是if(b>=97 && b<=122)
,而是将b
限制在小写范围内。
我个人更喜欢写作if (97 <= b && b <= 122)
,这样可以很容易地看到它的范围。
答案 1 :(得分:1)
如果您使用库<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;
}