所以昨晚我问了一个关于我想要练习的三角计算器的问题,我又回来了一个与我上一个问题非常相关的问题。我从昨晚开始修改计算器,但由于一些奇怪的原因,其中一个if语句正在通过给出不同if语句的测试。这是我的代码 -
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int x;
float o, h, a, S, C, T;
enum { sine, cosine, tangent};
printf("Enter the value for the function you wish to calculate\n(Sine = 0 Cosine = 1 Tangent = 2): ");
scanf("%f", &x);
if(x == 0)
{
printf("Enter the value of the opposite leg: ");
scanf("%f", &o);
printf("Enter the value of the hypotenuse: ");
scanf("%f", &h);
S = o / h;
printf("The sine is equal to %f", S);
}
else if(x < 2, x > 0)
{
printf("Enter the value of the adjacent leg: ");
scanf("%f", &a);
printf("Enter the value of the hypotenuse: ");
scanf("%f", &h);
C = a / h;
printf("The cosine is equal to %f", C);
}
else if(x == 2)
{
printf("Enter the value of the opposite leg: ");
scanf("%f", &o);
printf("Enter the value of the adjacent leg");
scanf("%f", &a);
T = o / a;
printf("The tangent is equal to %f", T);
}
else
{
printf("Wat da fack");
}
return 0;
}
切线的余弦测试通过会发生什么,切线功能不起作用。和以前一样,我还是很新,所以对我来说很容易..顺便说一句,我有两个测试条件的余弦的原因是它不会运行,除非我有这样的,sny洞察到这是欣赏太
答案 0 :(得分:4)
if (x < 2, x > 0)
没有按你的想法行事。它应该是if (x<2 && x>0)
;阅读 C
如果您编译了所有警告和调试信息(例如使用gcc -Wall -g
),您可能会收到警告。您应该学习如何使用调试器(例如Linux上的gdb
)。
编译器(至少是GCC)应警告scanf("%f", &x);
x
int
为scanf (" %d", &x);
。你可能想要scanf
,你可能想测试printf
的结果(它给你成功读取元素的数量)。
你很可能需要用换行符结束每个printf("Enter the value of the opposite leg:\n");
格式字符串(例如代码fflush
) - 或者经常调用scanf
- 你最好放一个您的scanf(" %f", &a)
格式字符串中的空格,例如{{1}}
答案 1 :(得分:2)
在scanf("%f", &x);
中,将%f
替换为%d
,因为x
是int
,但这不是主要问题,
问题出在if
语句条件
comma(,)
未用于AND
目的,您必须使用&&
,,所以您的州会成为,
if ((x < 2) && (x > 0))
修改强>
当您从用户处获取%f
时,请将%d
替换为scanf
中的x
...
scanf("%d", &x);
这将解决您的问题。
答案 2 :(得分:2)
正如其他人所说,问题似乎出现在你的第二个else if()
声明中。基本上讨厌的是,x < 2
和x > 0
语句都被执行,但只有x > 0
被用来测试条件。因此,余弦函数的测试也将通过切线函数,即cosine > 0
,tangent > 0
,并且永远不会执行切线函数的测试。
执行比较的更好方法是使用x == 1
进行测试,或者使用else if(x > 0 && x < 2)