69,381
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
void showmenu(void);
int getchoice(int high, int low);
int main(void)
{
int code;
showmenu();
while((code = getchoice(4,1)) != 4)
{
printf("I like choice %d.\n",code);
showmenu();
}
return 0;
}
void showmenu(void)
{
printf("Please choose one of following:\n");
printf("1) copy files 2) move files\n");
printf("3) remove files 4) quit\n");
printf("Enter the number of your choice:\n");
}
int getchoice(int high, int low)
{
int num, good;
good = scanf("%d", &num);
while(good == 1 && (num < low || num > high))
{
printf("%d is not a valid choice; try again.\n", num);
showmenu();
good = scanf("%d", &num);
}
if(scanf("%d", &num) != 1)
{
printf("Input error.");
num = 4;
}
printf("%d", num);
return num;
}
#include<stdio.h>
void showmenu(void);
int getchoice(int high, int low);
int main(void)
{
int code;
showmenu();
while((code = getchoice(4,1)) != 4)
{
printf("I like choice %d.\n",code);
showmenu();
}
return 0;
}
void showmenu(void)
{
printf("Please choose one of following:\n");
printf("1) copy files 2) move files\n");
printf("3) remove files 4) quit\n");
printf("Enter the number of your choice:\n");
}
int getchoice(int high, int low)
{
int num, good;
good = scanf("%d", &num);
while(good == 1 && (num < low || num > high))
{
printf("%d is not a valid choice; try again.\n", num);
showmenu();
good = scanf("%d", &num);
}
//if(scanf("%d", &num) != 1)
if(good != 1)
{
printf("Input error.");
num = 4;
}
printf("%d", num);
return num;
}
参考一下吧
因为while后面还有一个scanf,所以你需要输入两次才行。但是,修改一下,改成如上就可以了。不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
while (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
while (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。