gpt4 book ai didi

c - y/n 循环位于函数末尾

转载 作者:行者123 更新时间:2023-11-30 18:35:24 24 4
gpt4 key购买 nike

晚上好,

这是我的代码。我正在制作一个小计算器,但我在最后努力让函数通过 y/n 循环重复。我看过其他人,但似乎无法得到正确的答案。谢谢。

#include <stdio.h>

int main()
{
int n, num1, num2, result;
char answer;
{
printf("\nWhat operation do you want to perform?\n");
printf("Press 1 for addition.\n");
printf("Press 2 for subtraction.\n");
printf("Press 3 for multiplication.\n");
printf("Press 4 for division.\n");
scanf("%d", &n);
printf("Please enter a number.\n");
scanf("%d", &num1);
printf("Please enter the second number.\n");
scanf("%d", &num2);
switch(n)
{
case 1: result = num1 + num2;
printf("The addition of the two numbers is %d\n", result );
break;
case 2: result = num1 - num2;
printf("The subtraction of the two numbers is %d\n", result );
break;
case 3: result = num1 * num2;
printf("The multiplication of the two numbers is %d\n", result );
break;
case 4: result = num1 / num2;
printf("The division of the two numbers is %d\n", result );
break;
default: printf("Wrong input!!!");
}
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
while(answer == 'y');

}
return 0;
}

最佳答案

您有此代码

  char answer;
{
printf("\nWhat operation do you want to perform?\n");
//...
//... more code
//...
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
while(answer == 'y');

}

尝试将其更改为:

  char answer;
do {
printf("\nWhat operation do you want to perform?\n");
//...
//... more code
//...
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
} while(answer == 'y');

所以基本形式是:

do {
// code to repeat
} while (Boolean-expression);

顺便说一句 - 您应该始终检查 scanf 返回的值

示例:

if (scanf("%c", &answer) != 1)
{
// Add error handling
}

另请注意,您通常需要在 %c 之前添加一个空格,以删除输入流中的任何空格(包括换行符)。喜欢

if (scanf(" %c", &answer) != 1)
{
// Add error handling
}

关于c - y/n 循环位于函数末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46777605/

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