尝试编译时出现错误"expected unqualified-id before ‘{’ token {"

Getting error "expected unqualified-id before ‘{’ token {" when trying to compile

本文关键字:before token unqualified-id expected 错误 编译      更新时间:2023-10-16

尝试编译程序时出现以下错误:

错误:在"{"令牌 { 之前应为非限定 ID

这是代码:

#include <iostream>
#include <vector>

using namespace std;
{
vector<int> prime;

bool is_prime(int n)
{
for (int p = 0; p<prime.size(); ++p)
    if (n%prime[p]==0) return false;    // no remainder: prime[p] divided
return true;    // no smaller prime could divide
}
int main()
{
do
 {
prime.push_back(2); // consider the smallest prime
for (int i = 3; i<=100; ++i)    // test all integers [3:100]
    if (is_prime(i)) prime.push_back(i);    // add new prime to vector
cout << "Primes: ";
for (int p = 0; p<prime.size(); ++p)
    cout << prime[p] << 'n';
  }

}
#include <iostream>
#include <vector>
using namespace std;
vector<int> prime;
bool is_prime(int n)
{
for (int p = 0; p<prime.size(); ++p)
   if (n%prime[p]==0) return false;    // no remainder: prime[p] divided
return true;    // no smaller prime could divide
}
int main()
{

prime.push_back(2); // consider the smallest prime
for (int i = 3; i<=100; ++i)    // test all integers [3:100]
if (is_prime(i)) prime.push_back(i);    // add new prime to vector
cout << "Primes: ";
for (int p = 0; p<prime.size(); ++p)
cout << prime[p] << 'n';
}

这是无错误的代码版本。

你不需要在主函数中"do {",因为主函数中的所有行都是在程序运行时执行的!做而循环用于循环。在这里阅读更多关于它的信息:http://en.wikipedia.org/wiki/Do_while_loop,但是当需要执行行而不检查任何条件时(就像在这种情况下),你不需要做 while 循环。

使用命名空间 std 后也不需要 "{";

正如有人评论的那样,我也强烈建议您阅读一本书来清除这些基础知识!

相关文章: