[尝试制作一个基于用户输入来计算数组中值的计算器。但是当我让'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
。
和的初始值为1,这就是为什么它再加1的原因。我们也不能将其保持为0,因为那样会弄乱'*'和'/'大小写。我已经为所有情况添加了初始和值。另外,我建议您使用切换用例,而不要使用if,else语句。