要求用户重复程序或退出 C [英] Ask user to repeat the program or exit in C

查看:52
本文介绍了要求用户重复程序或退出 C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In this very basic program which ask the user to input two numbers, and then the program will sum these numbers together. I want at the end to ask the user if he/she want to repeat the program again or to exit the program! for example if he/she press y the program will reask the user to input two number, otherwise the program will be closed. How to do it ?

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);
}

推荐答案

int main(void) {
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\n",sum);
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}

这使用了 do-while 循环.它将一直持续到 do-whilewhile 中的条件返回 false.

This uses a do-while loop. It will continue till the condition in the while of the do-while will return false.

简单来说,每当用户输入 yY 时,while 循环将返回 true.因此,它将继续.

In simple words, whenever the user enters y or Y, the while loop will return true. Thus, it will continue.

检查这个示例和do-while教程循环.

这篇关于要求用户重复程序或退出 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆