【问题标题】:error: expected ‘}’ at end of input — when all brackets are closed [duplicate]错误:输入末尾的预期“}”-当所有括号都关闭时[重复]
【发布时间】:2018-07-17 14:02:26
【问题描述】:

我写的这个程序应该打印一些数字:

#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
 }
 ^

虽然第一个错误是可以理解的,因为函数定义不能在其他函数中,但我不理解第二个错误,因为我所有的括号都已关闭。

为什么编译器会产生第二个错误?

【问题讨论】:

  • 你不能在另一个函数中定义一个函数。
  • @Bathsheba 有吗?我数了 4 { 和 4 }。请注意 if 语句中有一个大括号。
  • 您(缺少)格式使您的代码难以阅读,因此您更有可能犯这种错误
  • 我的错误是error: a function-definition is not allowed here before ‘{’ token
  • 这仍然是一个低质量的问题,重复了许多问题,没有任何文字解释,应该保持关闭

标签: c++


【解决方案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() 之前声明您的函数,然后再定义它。

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2018-10-04
    • 2021-03-15
    相关资源
    最近更新 更多