C++:"Expected '(' for function-style cast or type construction"错误
C++: "Expected '(' for function-style cast or type construction" Error
有人知道我的代码出了什么问题吗?我正在尝试创建一个程序来输出整数向量的交替和。例如,如果输入为 1 2 3 4,则结果为 1-2+3-4 = -2。如果用户输入"y",程序也将继续运行,当用户输入"n"时,程序也会停止。
我知道我的代码中存在语法错误:将整数输入为向量时以及调用alternating_sum函数时。不过,我不知道如何解决它。
这是我到目前为止所拥有的:
#include <iostream>
#include <vector>
using namespace std;
double alternating_sum(vector<int> numbers)
{
double sum = numbers[0];
for (int i = 1; i < numbers.size(); i++) // i = position in vector
{
if (i % 2 == 0) // if i is even
{
sum += numbers[i];
}
else // if i is odd
{
sum -= numbers[i];
}
}
return sum;
}
int main()
{
char response;
while (true)
{
cout << "Enter a list of integers: ";
cin >> vector<int> input;
double result = alternating_sum(vector<int> input);
cout << "Continue (y/n)? ";
cin >> response;
if (response == 'n')
{
break;
}
}
return 0;
}
正如其他人所提到的,有很多问题需要解决。举出想到的第一个,cin >> vector<int> input;
你在输入语句中声明了一个变量,但你也不能cin >>
向量,它在语法上不起作用。
您必须循环以获取用户提供的每个数字输入,并以这种方式将其放入数组中。为此,您可以编写以下内容:
vector<int> v;
int input;
while (cin >> input)
v.push_back(input);
这样做的原因是cin >>
实际上只吃第一个输入值,直到它看到空格或EOF
,所以如果你输入类似1 2 3 4 5
行的东西,cin >> input
只会在第一次调用时1
抓取值。
double result = alternating_sum(vector<int> input);
您还需要将其写为
double result = alternating_sum(input);
由于输入已经定义,因此无需再次执行此操作:)
@samualnj也给了你另一个答案!
万事如意,继续编码:D
相关文章:
- "Called Object Type is Not a Function or Pointer" 与 typedef 和类
- 编译为 cuda 内核调用提供了"expression must have integral or unscoped enum type"
- C++ 结构数组 - "This declaration has no storage class or type specifier"
- C++:"Expected '(' for function-style cast or type construction"错误
- 模板元编程:"does not have integral or enumeration type"
- C++ 中的"this declaration has no storage class or type specifier"错误
- 如何修复派生类给出错误'declaration has no storage class or type specifier'?
- "declaration has no storage class or type specifier" C++
- vtkTypeTraits.h 错误:"Type long is not 4 or 8 bytes in size."
- 如何解决"expected constructor, destructor, or type conversion before ‘(’ token"错误?
- 字符串初始化失败:"expression must have integral or unscoped enum type"
- 内存集调用位置的"error: expected constructor, destructor, or type conversion before '(' token"
- 错误"this declaration has no storage class or type specifier"
- 使用字符串流时出现"Declaration has no storage class or type specifier"错误
- 模板类编译"expected constructor, destructor, or type conversion before ‘<’ token"错误
- 错误 : "expected constructor, destructor, or type conversion before 'typedef' "
- "Expected '(' for function-style cast or type construction"错误是什么意思?
- C++编译错误"expected constructor, destructor, or type conversion before ‘class’"
- C++ 代码中的错误 "expected constructor, destructor, or type conversion before ‘(’ token" 和"no matching fun
- 函数声明错误,"expected constructor, destructor, or type conversion before ';' token"