c - 重复程序提示
问题描述
当前的问题在于Evaluate another interval (Y/N)?
提示。假设我运行程序 4 次;为了结束它,它需要我输入N
4 次。
int main() {
int trap, test;
double low, hi;
char repeat, c;
//Gather End Points
do {
printf("Enter endpoints of interval to be integrated (low hi): ");
test = scanf("%lf %lf", &low, &hi);
if (test != 2) {
printf("Error: Improperly formatted input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (low > hi)
printf("Error: low must be < hi\n");
} while ((test != 2 || low > hi));
//Gather amount of triangles
do {
printf("Enter number of trapezoids to be used: ");
test = scanf("%d", &trap);
if (test != 1) {
printf("Error: Improperly formated input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (trap < 1)
printf("Error: numT must be >= 1\n");
} while ((trap < 1 || test != 1));
//Output integrate
printf("Using %d trapezoids, integral between %lf and %lf is %lf",
trap, low, hi, integrate(low, hi, trap));
//Prompt user for another time
while (1) {
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat) {
case 'Y':
main();
case 'y':
main();
case 'N':
return 0;
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
return 0;
}
我希望这样无论我运行什么程序,当我输入 one 时它都会关闭N
。
解决方案
有很多方法可以实现你想要的,但main
递归调用不是一个好主意。
更改程序的一种非常简单的方法是添加一个额外的while(1)
级别。就像是:
int main(void)
{
char repeat;
while(1){ // Outer while to keep the program running
printf("running program\n");
// Put your program here
printf("program done\n");
repeat = '?';
while(repeat != 'y' && repeat != 'Y'){ // Repeat until input is 'Y' or 'y'
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
break;
case 'N':
case 'n':
return 0; // Stop if input is 'n' or 'N'
default:
printf("Error: must enter Y or N");
}
}
}
return 0; // This will never be reached
}
另一种方法(一种更简单的方法,IMO)是将您询问用户的代码放入您从中调用的函数中main
。喜欢:
int continueProg()
{
char repeat = '?';
while(1){
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
return 1;;
case 'N':
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
}
int main(void)
{
do {
printf("running program\n");
// Put your program here
printf("program done\n");
} while(continueProg());
return 0;
}
顺便说一句:看看getchar
而不是使用scanf
推荐阅读
- docker - 无论如何,在 Heroku 中安装我的应用程序文件后是否可以检查它?
- c++ - 从函数返回二维动态数组
- r - 错误消息 - 找不到 object.size 函数
- javascript - 是否可以在 iframe 中访问父文档?
- powershell - 如何从 cmd 执行此 PowerShell 命令?
- c++ - 为什么在将中间结果分配给 int 之前将其转换为 long?
- r - 我无法在块下方绘制表格
- r - 合并两个列表以获得 r 中的字符列表
- html - 如何让css动画包含换行符?
- vim - Vim 搜索替换正则表达式 if this, not that, and not that