为什么我的代码在形状“矩形”的无限循环中?

时间:2016-03-03 08:01:22

标签: c++

这是代码

#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();”功能正常,有人可以告诉我,如果我正确调用它。

3 个答案:

答案 0 :(得分:2)

在使用它们的值之前,请初始化非静态局部变量。

试试这个:

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;
    }

}

答案 1 :(得分:1)

您永远不会初始化宽度或长度。用户输入它们的块由if语句保护,该语句总是评估为false。

答案 2 :(得分:1)

在函数shape中,变量void printRectangles(){ int length; int width; int base; string shape; ^^^^^^^^^^^^ //... 是一个空字符串

if ("rectangle" == shape)
{
//..

所以if语句

if ("Rectangle" == shape)
{
//...

false

将永远执行,因为条件评估为length

因此变量widthfor (int row = 1; row <= width; row++) { for (int col = 1; col <= length; col++) { cout << "*"; } cout << endl; } 将具有不确定的值和循环

void printRectangles()
{
    int length;
    int width;

    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 printRectangles( const std::string &shape );

或者将该函数声明为具有指定形状的参数。例如

{{1}}

并检查函数中的形状。