我做了什么?如果声明工作......有点

时间:2012-12-31 08:23:12

标签: c

所以昨晚我问了一个关于我想要练习的三角计算器的问题,我又回来了一个与我上一个问题非常相关的问题。我从昨晚开始修改计算器,但由于一些奇怪的原因,其中一个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洞察到这是欣赏太

3 个答案:

答案 0 :(得分:4)

if (x < 2, x > 0)没有按你的想法行事。它应该是if (x<2 && x>0);阅读 C

中的comma operator

如果您编译了所有警告和调试信息(例如使用gcc -Wall -g),您可能会收到警告。您应该学习如何使用调试器(例如Linux上的gdb)。

编译器(至少是GCC)应警告scanf("%f", &x); x intscanf (" %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,因为xint,但这不是主要问题,

问题出在if语句条件

comma(,)未用于AND目的,您必须使用&& ,,所以您的州会成为,

if ((x < 2) && (x > 0))

修改

当您从用户处获取%f时,请将%d替换为scanf中的x ...

scanf("%d", &x);这将解决您的问题。

答案 2 :(得分:2)

正如其他人所说,问题似乎出现在你的第二个else if()声明中。基本上讨厌的是,x < 2x > 0语句都被执行,但只有x > 0被用来测试条件。因此,余弦函数的测试也将通过切线函数,即cosine > 0tangent > 0,并且永远不会执行切线函数的测试。

执行比较的更好方法是使用x == 1进行测试,或者使用else if(x > 0 && x < 2)