当前问题与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;
}
我希望这样做,以便无论我运行的程序是什么,当我键入一个N
时都会关闭。
答案 0 :(得分:1)
有很多方法可以实现所需的目标,但是递归调用const img = this.editor.getImageScaledToCanvas().toDataURL();
并不是一个好主意。
更改程序的一种非常简单的方法是添加一个附加的main
级。像这样:
while(1)
另一种方法(一种更简单的方法,IMO)是将您要求用户输入的代码放入从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
}
调用的函数中。喜欢:
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
答案 1 :(得分:0)
您的程序中存在多个问题:
[]
的返回值,并且正确清除了未决的输入,但是您没有处理文件的潜在结尾,从而导致无休止的循环。scanf()
必须定义为c
,以容纳int
返回的所有值:256个类型为getchar()
的值和特殊值unsigned char
。 / li>
EOF
递归重复该程序的操作,需要多个main()
答案。相反,您应该添加一个外部循环,并在N
答案或文件条件结束时退出该循环。这是修改后的版本:
N