gpt4 book ai didi

c - 如何重新启动C语言程序?

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

嗨,我是 C 新手,我编写了一个简单的程序。如果用户选择了错误的选择,我想重新启动程序,代码如下:

#include <stdio.h>
#include <cs50.h>
int main(void){
char choices;
float math, pc, svt, eng, philo;
do {
do {
printf("Enter your math score: ");
math = GetFloat();
}
while( math>20 || math<0);
do {
printf("Enter your pc score: ");
pc = GetFloat();
}
while(pc>20 || pc<0);
do {
printf("Enter your svt score: ");
svt = GetFloat();
}
while(svt>20 || svt<0);
do {
printf("Enter your eng score: ");
eng = GetFloat();
}
while(eng>20 || eng<0);
do {
printf("Enter your philo score: ");
philo = GetFloat();
}
while(philo>20 || philo<0);
printf("Are you pc or sm?\n");
printf("Write 1 for pc. 2 for sm\n");
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");

}

printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
} while (choices == 'Y' || choices == 'y');


}

所以我在这里的意思是,我想在 else block 中插入代码来重新启动程序并给用户另一个时间。如果我能让他在 1 或 2 之间再次选择,那就太好了。

如果您有任何建议或改进,请随时发表评论。谢谢:)

最佳答案

您需要的是 do while 循环围绕选择代码:

int choice;

do {
choice = GetInt();
if (choice == 1) {
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if (choice == 2) {
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else {
printf("You've picked the wrong choice, try again.\n");
}
} while(choice < 1 || choice > 2)

关于c - 如何重新启动C语言程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006083/

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