gpt4 book ai didi

当我输入 "sine"时,C 计算器程序一直出错?

转载 作者:太空狗 更新时间:2023-10-29 15:26:58 25 4
gpt4 key购买 nike

大家好,我是编程新手,现在已经在计算器上工作了一段时间。我正在尝试添加一些三角函数,但我在使用正弦函数时遇到了问题。其他函数有效(+、-、*、/),但是当我输入“正弦”时,它会跳到代码中表示它是错误函数的部分。请帮助我的代码。谢谢!

#include <stdio.h>
#include <math.h>


int main()
{

float firstnum, secondnum, angle, answer, pi;
char function, sine;


pi = atan(1.0)*4;


printf("\nHello and welcome to my calculator!\n");

while(1)
{

printf("\nPlease input the function you would like to use. These include +, -, *, /, sine.\n");
scanf("%s", &function);



switch(function)
{
case '+':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum+secondnum;
break;

case '-':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum-secondnum;
break;

case '*':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum*secondnum;
break;

case '/':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum/secondnum;
break;

case 'sine':
printf("\nPlease enter the angle.\n");
scanf("%f", &angle);
answer = sin(angle);
break;



default: printf("Sorry, that is an incorrect function. The only available choices are +, -, *, /, sine.");
break;
}

printf("Your answer is %f \n", answer);
printf("\nWhen you are ready to quit, simply press Ctrl + C or just hit the X button in the top right.\n");
}

return 0;
}

最佳答案

'sine'

这是一个多字 rune 字。 function 是单个字符。它的整数值在 switch 语句中检查。您可能永远无法以您尝试这样做的方式使用与 sine 匹配的用户的单个字符。改为读取字符串 (a char*)。

来自标准:

C99 6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."

关于当我输入 "sine"时,C 计算器程序一直出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com