尝试编译时出错

时间:2014-12-14 13:46:24

标签: c++

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

错误:在'{'标记之前预期的unqualified-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';

  }


}

希望有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

#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';

}

这是无错误的代码版本。

你不需要&#34;做{&#34;在main函数中,当程序运行时,将执行main中的所有行! while循环用于循环。在这里阅读更多相关信息:http://en.wikipedia.org/wiki/Do_while_loop,但是当需要执行这些行而不检查任何条件时(例如在这种情况下),您不需要在循环中执行。

也不需要&#34; {&#34;使用命名空间std后;

如某人所评论,我也强烈建议您阅读一本书来清除这些基础知识!