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

标签 c loops while-loop do-while cs50

嗨,我是 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/

相关文章:

c - 字符串比较在 C 语言中无法按预期工作

c - SDL2_gfx 函数不起作用

c++ - 我怎样才能重置我的程序? (不使用 goto)

java - 使用数组的直方图,最终直方图中不包括 int 10

Bash While 循环按行读取文件并在特定行退出

java - 为什么我的 while 循环不终止?

C图。无法将边添加到邻接表中

c++ - 具有多个文件的 LOG4CPP

JavaScript forEach : mutate elements

java - 为什么我们必须使用 "while"来检查竞争条件而不是 "if"