該程序將要求一個數值,並只接受正值。字母或符號的輸入將導致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