c - 在 C 中要求用户重复该程序或退出

标签 c printf

在这个非常基本的程序中,要求用户输入两个数字,然后程序将这些数字相加。我想在最后询问用户是否想再次重复该程序或退出该程序!例如,如果他/她按 y,程序将要求用户输入两个数字,否则程序将关闭。怎么做?

main(){
float x,y,sum;
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f",sum);
}

最佳答案

main(){
    float x,y,sum;
    char ch;

    do{
    printf ("Enter the first number:");
    scanf ("%f",&x);
    printf ("Enter the second number:");
    scanf ("%f",&y);
    sum=x+y;
    printf ("The total number is:%f",sum);
    printf ("Do you want to continue: y/n");
    scanf (" %c", &ch);
    } while(ch == 'y');
    }

或者您也可以尝试这个:

main(){
    float x,y,sum;
    char ch;

    do{
    printf ("Enter the first number:");
    scanf ("%f",&x);
    printf ("Enter the second number:");
    scanf ("%f",&y);
    sum=x+y;
    printf ("The total number is:%f",sum);
    printf ("Do you want to continue: y/n");
    ch = getchar();
    getchar();
    } while(ch == 'y');
    }

关于c - 在 C 中要求用户重复该程序或退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34941692/

相关文章:

c - 如何从打开的 cv 中的文件夹中读取多个图像(使用 C)

c++ - BCB swprintf 不工作

c++ - Windows CPP InjectSyntheticPointerInput

c - 在 printf 中用星号填充?

c++ - %x printf说明符的类型是否为long OK?

C 客户端/服务器与 fprintf 通信?

c++ - 二维数组中的按行和按列总计

c - 依靠 strtok_r 的内部指针安全吗?

c - 使用 printf 打印出一个 unicode 字符

c - 删除新行和 printf 的问题