函数中的循环运行超出了需要

Loop in function running more than it needs to

本文关键字:运行 循环 函数      更新时间:2023-10-16

在我正在处理的一个问题中,我有一个函数可以检查矩形块中的球形和圆柱形孔的数量是否大于零。在这个问题上,我必须调用函数两次。我的问题是,我第一次调用函数"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];
    }
}
}

假设您的第二个Check函数实际上是HoleCheck,这是一个拼写错误:

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

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