谁可以帮我处理矩形区域。我无法做到万无一失,即禁止输入字母和负数。我只是在创建引用字母的第一个条件时无法创建第二个条件。我怎么能这样做,或者我甚至必须从头开始改变程序。我只需要找到一个矩形区域。
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
#include <locale.h>
#include <Windows.h>
int _tmain(int argc, char* argv[])
{
printf("Area of a Rectangle. Press Enter to start\n");
system("pause");
float a, s, d;
do
{
fflush(stdin);
system("cls");
printf("Enter the lengths of the rectangle\n");
scanf_s("%f", &a);
scanf_s("%f", &s);
if (getchar() != '\n') {
while (getchar() != '\n')
;
printf("Your data is wrong\n");
system("pause");
continue;
}
break;
} while (true);
d = a*s;
printf(" Area is %.1f ", d);
system("pause");
return 0;
}
答案 0 :(得分:2)
此程序将询问数值并仅接受正值。字母或符号的输入将导致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;
}
答案 1 :(得分:1)
浮动的一个万无一失的scanf
看起来像这样
float getFloat() {
float in;
while(scanf("%f", &in) != 1 && getchar() != '\n') {
fflush(stdin);
fprintf(stderr, "Wrong input, enter again : ");
}
return in;
}
这对我有用。然后,您的代码将简化为
float a = getFloat();
float b = getFloat();
printf("Area is %.1f", a * b);