我刚刚了解了if语句,并尝试制作某种计算器,但是它不起作用。它要求您输入一个操作(目前仅适用于加法运算),然后要求输入两个整数。它非常简单,但是不起作用。该错误可能对你们来说很明显,但我只是看不到它。请帮忙!这是代码:

int main()
{
int operation;
int addition;
float firstNumber;
float secondNumber;
printf("Type in an operation.\n");
scanf(" %s", operation);


if(operation = addition){
printf("Please, enter an integer.\n");
scanf(" %f", &firstNumber);

printf("Please, enter a second integer.\n");
scanf(" %f", &secondNumber);

printf("Answer: %d", firstNumber + secondNumber);
}else{
printf("Sorry, only addition works..");
}
return 0;
}

最佳答案

为什么您的代码应该工作?

int operation;
/* int for storing a string? huh?
 * or were you thinking about function pointers ?
 * Normally you would use a char[]
 */


scanf(" %s", operation);
/* Using %s specifier looks weird .
 * Also scanf is reading into operation and not &operation
 * So is having a space in the in the beginning of the format string.
 */

int addition;
 /* Automatic variables are not initialized as per the standard
  * But what about the type?
  * Were you intending to do something like char addition[]="addition"
  */

if(operation = addition)
/* If you somehow manage to get to this point
 * you have another problem you do an assignment in the statement using =
 * You should have been  using ==
 */

关于c - 请向我解释为什么带有if语句的简单C程序不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36805806/

10-11 23:11
查看更多