在函数中循环运行超过它需要的

时间:2014-04-17 23:54:07

标签: c++ function loops

在我正在研究的问题中,我有一个功能,检查矩形块中的球形和圆柱孔的数量是否大于零。在这个问题上,我必须调用该函数两次。我的问题是我第一次调用函数'HoleCheck'是运行两次并假设为圆柱孔输入零并让我重新输入球形孔的值。如何才能使它只运行一次球形孔检查?

#include <iostream>
#include <string>

using namespace std;

void Check(double arr1[], string arr2[]);
void HoleCheck(int arr3[], string arr4[]);


int main()
{

double DimArray[3];
string MyArray[3] = { "Height", "Length", "Width"};
int totalholes[2];
string holes[2] = { "Spherical", "cylindrical"};

cout << "Enter the height, length and width of rectangle in centimeters: ";
cin >> DimArray[0] >> DimArray[1] >> DimArray[2];
Check(DimArray, MyArray);

cout << "How many spherical bubbles are present? ";
cin >> totalholes[0];
HoleCheck(totalholes, holes);
cout << "How many cylindrical holes are present? ";
cin >> totalholes[1];
HoleCheck(totalholes, holes);

return 0;
}

void Check(double arr1[], string arr2[])
{
int i;
for (i = 0; i < 3; i++)
{
    while (arr1[i] <= 0)
    {
        cout << "Your entered " << arr2[i] << " is less than zero!\n";
        cout << "Please re-enter a valid number --> ";
        cin >> arr1[i];
    }
}
}
void Check(double arr1[], string arr2[])
{
int z;
for (z = 0; z < 2; z++)
{
    while (arr3[z] <= 0)
    {
cout << "The number of " << arr4[z] << " holes must be greater than 0.\n";
        cout << "Please re-enter a valid number --> ";
        cin >> arr3[z];
    }
}
}

1 个答案:

答案 0 :(得分:1)

假设您的第二个Check函数实际上是HoleCheck而且这是一个错字:

您的HoleCheck功能检查其arr3的两个元素,但在您向totalHoles[1]输入任何值之前,您正在调用它。

要么只是删除对HoleCheck的第一次调用,要么更改它,以便告诉它要检查数组中的哪个条目。