该程序将要求一个数值,并只接受正值。字母或符号的输入将导致scanf()
失败,程序将清除输入缓冲区并重试。在这个例子中,输入字母'q'将退出程序。你可以适应你的情况。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i = 0;
float n = 0.0f;
do {
printf("enter numeric value or q to quit\n");
if (scanf("%f",&n) != 1) {// scan one float
while ((i = getchar ()) != '\n' && i != 'q') {
//clear buffer on scanf failure
//stop on newline
//quit if a q is found
}
if (i != 'q') {
printf ("problem with input, try again\n");
}
}
else {//scanf success
if (n == fabs (n)) {
printf("number was %f\n", n);
}
else {
printf("positive numbers only please\n");
}
}
} while (i != 'q');
return 0;
}
这已经适应了上述功能。
#include <stdio.h>
float getfloat (char *prompt, int *result);
int main (int argc, char* argv[])
{
float width, height, area;
int ok = 0;
do {
printf("\n\tArea of a Rectangle.\n");
width = getfloat ("Enter the width of the rectangle or q to quit\n", &ok);
if (ok == -1) {
break;
}
height = getfloat ("Enter the height of the rectangle or q to quit\n", &ok);
if (ok == -1) {
break;
}
area = width * height;
printf(" Area is %.1f\n", area);
} while (1);
return 0;
}
float getfloat (char *prompt, int *result)
{
int i = 0;
float n = 0.0f;
*result = 0;
do {
printf("%s", prompt);
if (scanf("%f",&n) != 1) {// scan one float
while ((i = getchar ()) != '\n' && i != 'q') {
//clear buffer on scanf failure
//stop on newline
//quit if a q is found
}
if (i != 'q') {
printf ("problem with input, try again\n");
}
else {
*result = -1;
n = 0.0f;
}
}
else {//scanf success
if (n == fabs (n)) {
*result = 1;
}
else {
printf("positive numbers only please\n");
}
}
} while (*result == 0);
return n;
}
声明:'fflush(stdin)'在C标准中明确声明为不起作用。这是因为'fflush()'仅适用于输出流,而不适用于输入流。建议使用:'while(int ch = getchar()&& ch!= EOF && ch!='\ n');' – user3629249
变量名:'a''和'd'没有意义。你的代码应该总是使用有意义的名称来用于索引/循环计数器变量以外的变量建议:rectHeight rectWidth rectArea。 – user3629249
这一行:'printf(“输入矩形的长度\ n”);'并不真正告诉用户输入什么内容。建议:'printf(“输入矩形的长度宽度\ n”);'始终检查从scanf()函数系列调用返回的值,以确保操作成功。 – user3629249