c++ - C++:在数组中输入数字时,第一个数字为0

标签 c++ calculator iostream

试图使计算器能够根据用户的输入来计算数组中的值。但是当我让'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/

相关文章:

c++ - 如何在 C++ 中跳过读取文件中的一行?

c++ - 在 Visual C++ 中向我的项目添加 dll 时遇到问题

C#语言,计算器

c++ - 如果 'input' 是一个整数,为什么 cin.fail() 会传递 input=100a?

c++ - 当您将引用分配给新创建的堆栈分配对象时会发生什么?

c++ - 帮助使用 Visual Studio C++ 2010 中的 Eclipse 快捷方式

javascript - 基本 Jquery/Javascript 计算

c - 如何在C中使用带有字符的if语句

C++ 持久性生物操作

c++ - 在 Visual Studio 2010 中使用 C++ iostream