gpt4 book ai didi

c - 为什么我的程序在没有收到任何新输入的情况下循环?

转载 作者:行者123 更新时间:2023-12-04 05:10:09 24 4
gpt4 key购买 nike

我试图让我的程序在给出答案后重新开始。一旦我运行一次,它就不会再次运行。我想让它在用户不必再次启动程序的地方发挥作用。谢谢!

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


int main()
{
float firstnum, secondnum, answer;
char function;

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

start: //Area to loop to when program completes

printf("\nPlease input the function you would like to use. These include +, -, *, /.\n"); //Asking for function input

scanf("%c", &function); //Receiving Function Input

printf("\nNow please input the two variables.\n"); //Asking for variables

scanf("%f", &firstnum);

scanf("%f", &secondnum); //Receiving Input for Variables

if (function == '+') //Doing calculation
{
answer = firstnum+secondnum;
}
else if (function == '-')
{
answer = firstnum-secondnum;
}
else if (function == '*')
{
answer = firstnum*secondnum;
}
else if (function == '/')
{
answer = firstnum/secondnum;
}
else
{
printf("Sorry that was an incorrect function. The correct inputs are +, -, *, /."); //If they don't follow the directions
}

printf("Your answer is %f \n", answer); //Answer

goto start; //Loop

return 0;

}

最佳答案

这就是您使用循环的原因。 (并尽量不要为此使用 goto)。

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


int main() {

float firstnum, secondnum, answer;
char function, buffer[2];

while(1) {

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

printf("\nPlease input the function you would like to use. These include +, -, *, /.\n");
scanf("%s", &buffer);
function = buffer[0];
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
if (function == '+') answer = firstnum+secondnum;
else if (function == '-') answer = firstnum-secondnum;
else if (function == '*') answer = firstnum*secondnum;
else if (function == '/') answer = firstnum/secondnum;
else printf("Sorry that was an incorrect function. The correct inputs are +, -, *, /.");

printf("Your answer is %f \n", answer);
}

return 0;
}

这应该是一个无限循环,所以使用用户输入到 break;退出程序的循环

注意:我已将 scanf %c 替换为 %s 以指示字符串的输入并使用了缓冲区。
 scanf("%s",&buffer); function = buffer[0];

(根据评论中的讨论更新)

关于c - 为什么我的程序在没有收到任何新输入的情况下循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14993841/

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