我写的这个程序应该打印一些数字:
#include <iostream>
using namespace std;
int main()
{
int hitung(int A[], int n)
{
int jumlah = 0;
for (int i = 0; i < n; i++)
{
jumlah = jumlah + A[i];
if (i % 2 == 1)
{
cout << A[i];
}
}
return jumlah;
}
}
但是,当我尝试对其进行编译时,会收到以下错误消息:
main.cpp: In function 'int main()':
main.cpp:6:5: error: a function-definition is not allowed here before '{' token
{
^
main.cpp:18:1: error: expected '}' at end of input
}
^
虽然第一个错误是可以理解的,因为函数定义不能在其他函数中,但我不明白第二个错误,因为我所有的括号都已关闭。
为什么编译器会产生第二个错误?
答案 0 :(得分:1)
您已将函数hitung
定义为main()
。你不能这样做。但是,您可以执行以下操作:
#include <iostream>
using namespace std;
int hitung(int A[], int n)
{
int jumlah = 0;
for (int i = 0; i < n; i++)
{
jumlah = jumlah + A[i];
if (i % 2 == 1)
{
cout << A[i];
}
}
return jumlah;
}
int main()
{
int a[] = {1, 2, 3};
cout << hitung(a, 3) << endl;
return 0;
}
或者,您可以在main()
之前声明函数,然后在其后定义。