gpt4 book ai didi

c++ - 检查尺寸值及其内容的功能

转载 作者:太空宇宙 更新时间:2023-11-04 15:41:00 24 4
gpt4 key购买 nike

我正在尝试编写一个程序来检查矩形的尺寸是否大于零。在 void 函数 Check 中,我尝试使用数组来检查值并使用字符串来显示用户错误的维度。我收到一个错误,它“无法将参数 1 从‘double[6]’转换为‘double’。

#include <iostream>
#include <string>

using namespace std;

void Check(double, string);

int main()
{
const int size = 3;
double DimArray[size];
string MyArray[size] = { "Height", "Length", "Width"};

cout << "Enter the height, length and width of rectangle: ";
cin >> DimArray[0] >> DimArray[1] >> DimArray[2];

Check(DimArray, MyArray);

return 0;
}

void Check(double arr1[], string arr2[])
{
int i;
for (i = 0; i < 4; i++)
{
if (arr1[i] <= 0)
cout << "Your entered " << arr2[i] << "is less than zero!";
cout << "Please enter a valid number --> ";
cin >> arr1[i];
}
}

最佳答案

您应该正确声明函数。而不是

void Check(double, string);

应该有

void Check( double[], const std::string[], size_t );

也代替了函数体中的循环

for (i = 0; i < 4; i++)

必须有

for (i = 0; i < 3; i++)

函数可以定义为

void Check( double arr1[], const std::string arr2[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
while ( arr1[i] <= 0 )
{
std::cout << "Your entered " << arr2[i] << "is not positive!\n";
std::cout << "Please enter a valid number --> ";
std::cin >> arr1[i];
}
}
}

或者如果你将定义文件范围的常量

const size_t SIZE = 3;

然后可以简化函数定义(以及相应的声明)

void Check( double arr1[], const std::string arr2[] )
{
for ( size_t i = 0; i < SIZE; i++ )
{
while ( arr1[i] <= 0 )
{
std::cout << "Your entered " << arr2[i] << "is not positive!\n";
std::cout << "Please enter a valid number --> ";
std::cin >> arr1[i];
}
}
}

此外,最好定义一个 const char *

数组而不是 std::string(s) 数组
const char * MyArray[size] = { "Height", "Length", "Width"};

因为据我了解您不会更改它。

关于c++ - 检查尺寸值及其内容的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23144446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com