【发布时间】:2020-07-17 06:03:42
【问题描述】:
试图制作一个计算器,根据用户的输入计算数组中的值。但是当我离开 'p undefined 或 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
【问题讨论】:
-
为什么在这种情况下使用数组?从您的代码中我可以看出,您只是在尝试执行重复的数学运算,对吗?
-
您有未定义的行为,因为您尝试读取或写入
many[p]超出了范围。您已将数组声明为int many[p];,因此最后一个成员是many[p-1]。但是,正如@uglyCoder 所说,你为什么还需要一个数组呢?此外,可变长度数组 (VLA) 不是标准 C++!! -
总和是 4 而不是 3 的原因是您的 sum 变量从 1 开始。您应该将 sum 设置为输入的第一个数字(从 1 开始中断加法;从 0 开始中断乘法),并修复@AdrianMole 提到的未定义行为。
标签: c++ calculator iostream