这是代码
#include <iostream>
#include <string>
using namespace std;
void printTriangles(){
int length;
int width;
int base;
}
void printRectangles(){
int length;
int width;
int base;
string shape;
string repeat;
if ("rectangle" == shape)
{
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << endl;
cout << "Enter the width of the rectangle: ";
cin >> width;
}
if ("Rectangle" == shape)
{
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << endl;
cout << "Enter the width of the rectangle: ";
cin >> width;
}
for (int row = 1; row <= width; row++)
{
for (int col = 1; col <= length; col++)
{
cout << "*";
}
cout << endl;
}
}
void printSquares(){
int length;
int width;
int base;
}
int main ()
{
int length;
int width;
int base;
string shape;
string repeat;
cout << "I will print squares for you!"<< endl << "Rectangles and triangles, too!"<< endl << endl;
cout << "Enter the shape that you would like to print (rectangle, triangle, or square): ";
cin >> shape;
if ("rectangle" == shape)
printRectangles();
return 0;
}
当我输入 Rectangle 时,代码进入无限循环的星号,过去一天我一直在处理这个问题,但我还没有弄清楚我做错了什么。我相信我称我为“printRectangles();”功能正常,有人可以告诉我我是否正确调用了它。
最佳答案
在使用它们的值之前一定要初始化非静态局部变量。
试试这个:
void printRectangles(){
int length = 0; // initialize for in case the reading fails
int width = 0;
// This is a function for printing rectangle,
// so no checking for "rectangle", which is impossible because the input is not passed here
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << endl;
cout << "Enter the width of the rectangle: ";
cin >> width;
for (int row = 1; row <= width; row++)
{
for (int col = 1; col <= length; col++)
{
cout << "*";
}
cout << endl;
}
}
关于c++ - 为什么我的代码对于形状 "rectangle"处于无限循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766371/