#include <iostream>
#include <math.h>
using namespace std;
int main() {
double radius = 0.00;
double height = 0.00;
double width = 0.00;
double side = 0.00;
double Area = 0.00;
const double PI = atan(1.0)*4;
string input = "none";
while (input != "0") {
cout << "Shape Menu: \n (r) rectangle \n (s) square \n (c) circle \n (0) exit" << endl;
cin >> input;
if (input == "r"){
cout << "Please enter a floating point value for the height of the rectangle." << endl;
cin >> height;
cout << height;
while (height <= 0)
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Your input was invalid. Please input a floating point value greater than 0.";
cin >> height;
}
cout << "Please enter a floating point value greater than 0 for the width of the rectangle." << endl;
cin >> width;
while (width <= 0)
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Your input was invalid";
cin >> width;
}
Area = height*width;
cout << "The area of a rectangle with those dimensions is " << Area << "units squared." << endl;
}
else if(input == "s"){
cout << "Please enter a floating point value for the length of the side." << endl;
cin >> side;
if (cin.fail())
cout << "Please enter a floating point value.";
Area = side*side;
cout << "The area of a square with those dimensions is " << Area << "units squared" << endl;
}
else if(input == "c"){
cout << "Please enter a floating point value for the length of the radius." << endl;
cin >> radius;
if (cin.fail())
cout << "Please enter a floating point value.";
Area = radius*radius*PI;
cout << "The area of a circle with those dimensions is " << Area << "units squared." << endl;
}
else if(input == "0"){
break;
}
else{
cout << "Your input does not match one of the options suggested. Please type r, s, c to get the area of a shape, or type 0 to exit." << endl;
}
}
return 0;
}
我想寫一個程序,要求用戶從形狀菜單中選擇,然後要求爲每個類型確定該區域的某些輸入。我現在遇到的問題是試圖弄清楚如何在人們輸入半徑或非數字的高度和寬度的答案時引發錯誤。我試圖爲矩形寫入的錯誤對於初始不正確的輸入有效,但是一旦用戶被提示,就選擇另一個形狀,如果再次出現輸入錯誤,則會開始無限循環。這是什麼使一個無限循環
我無法重現你的錯誤,你的代碼確實是令人費解的。也許只是給出導致錯誤而不是口頭描述的確切輸入。還要檢查從cin讀取的if(cin >> foo)是否成功。 – pmr