试图使计算器能够根据用户的输入来计算数组中的值。但是当我让'p未定义或p = 1时,数组中的第一个值始终为0,这将给我同样的问题。它应该是用户输入的第一个值,依此类推。
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
总和应为3而不是4。
How many numbers are you working with today?
2
Enter number 1:
1
What would you like the numbers to do: (+ - / *)
+
Enter number 2:
2
What would you like the numbers to do: (+ - / *)
+
4
最佳答案
该程序无效,并且具有未定义的行为。
对于初学者,可变长度数组不是标准的C +功能
int p = 1, y = 0;
double sum = 1;
int many[p];
而且无论如何您都定义了一个带有一个元素的数组。因此,访问数组元素的唯一有效索引为0。
即使在使用数组的第一个语句中
cin >> many[p];
它的访问超出范围。
您应该使用标准的类模板
std::vector
。或实际上,您正在处理一个值,那么甚至没有使用容器的意义,而是定义一个标量对象而不是数组。
关于c++ - C++:在数组中输入数字时,第一个数字为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61039493/