今日主要写了一个很简单的函数,题目如下(源于C primer plus):
给定下面的输出:
Please choose one of the following:
1) copy files 2) move files
3) remove files 4) quit Enter the number of your choice:
a.编写一个函数,显示一份有4个选项的菜单,提示用户进行选择(输 出如上所示)。
b.编写一个函数,接受两个int类型的参数分别表示上限和下限。该函数 从用户的输入中读取整数。如果整数超出规定上下限,函数再次打印菜单 (使用a部分的函数)提示用户输入,然后获取一个新值。如果用户输入的 整数在规定范围内,该函数则把该整数返回主调函数。如果用户输入一个非 整数字符,该函数应返回4。
c.使用本题a和b部分的函数编写一个最小型的程序。最小型的意思是, 该程序不需要实现菜单中各选项的功能,只需显示这些选项并获取有效的响 应即可。
我的代码如下:
#include<stdio.h>
#define max(a,b) ((a>b) ? a:b)
#define min(a,b) ((a>b) ? b:a)
void Menu(void){
printf("Please choose one of the following:\n 1) copy file 2)move file\n 3)remove files 4)quit\n");
printf("Enter the number of your choice:\n ");
}
int determine(int a, int b) {
float c;
Menu();
scanf("%f", &c);/*注意scanf的书写方式*/
while (c > max(a, b) || c < min(a, b)) {
printf("The input is invalid,please try it agin: \n");
c = scanf("%f", &c);
}
if (c == (int)c)/*判断是否为整数*/
return c;
else
return 4;
}
int main() {
int choice;
choice = determine(1,4);
switch (choice)
{
case 1:
printf("copy file");
break;
case 2:
printf("move file");
break;
case 3:
printf("remove files");
break;
case 4:
printf("quit");
break;
default:
break;
}
}
题目答案代码:
#include <stdio.h>
void showmenu(void);
int getchoice(int, int);
int main()
{
int res;
showmenu();
while ((res = getchoice(1, 4)) != 4)
{
printf("I like choice %d.\n", res);
showmenu();
}
printf("Bye!\n");
return 0;
}
void showmenu(void)
{
printf("Please choose one of the 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 low, int high)
{
int ans;
int good;
good = scanf("%d", &ans);
/*当使用%d格式符读取整数时,如果成功读取一个整数值,则scanf()函数返回1;如果读取失败或遇到非数字字符,则返回0。
对于浮点数类型的读取,scanf()函数同样遵循这个规则。*/
while (good == 1 && (ans < low || ans > high))
{
printf("%d is not a valid choice; try again\n", ans);
showmenu();
scanf("%d", &ans);
/*当我们通过scanf的时候,如果参数列表是“%d”,
但是在运行的时候输入的是小数的话,那么第一次变量获取的是小数点前面的部分,如果小数点前面有整数的话,那么scanf就可以正常读取输入的值。
但是,倘若我们接下来还有一个scanf的话,那么该scanf就会去取输入的小数去掉整数的部分*/
}
if (good != 1)
{
printf("Non-numeric input.");
ans = 4;
}
return ans;
}
最大的收获是学习到了占位符是%d的情况下scanf输入小数的显示情况,为判断一个数是否为整数提供了新思路(while+scanf)