gpt4 book ai didi

c++ - 无法为整数类型的变量赋值

转载 作者:太空狗 更新时间:2023-10-29 20:36:22 28 4
gpt4 key购买 nike

我想找出1到100之间的质数。我遇到的问题是当程序将值2赋值给整数类型的变量j时。变量 j 的值不变。有谁知道为什么会这样?

Create a program to find all the prime numbers between 1 and 100.

One way to do this is to write a function that will check if a number isprime (i.e., see if the number can be divided by a prime numbersmaller than itself) using a vector of primes in order (so that if thevector is called primes, primes[0]==2, primes[1]==3, primes[2]==5,etc.). Then write a loop that goes from 1 to 100, checks each numberto see if it is a prime, and stores each prime found in a vector.Write another loop that lists the primes you found. You might checkyour result by comparing your vector of prime numbers with primes.Consider 2 the first prime.

#include <iostream>
#include <string>
#include <vector>

int main()
{
std::vector<int> primes = { 2 };
for (int i = 2; i <= 100; ++i)
for (int j = 2; j < i; ++j)
if (i % j == 0)
break;
else
primes.push_back(j);
for (int i = 0; i < primes.size(); ++i)
std::cout << primes[i] << ' ';
}

最佳答案

在你最初的实现中有一些错误:

  • 您在 primes vector 中添加元素的时间过早
  • 你对素数没有明确的定义
  • 您正试图将所有内容放在一个函数中

一些更干净的代码看起来有点像这样:

#include <iostream>
#include <string>
#include <vector>

namespace {
bool isPrime(const std::vector<int> &previousPrimes, int possiblePrime) {
for (auto prevPrime : previousPrimes)
if (possiblePrime % prevPrime == 0)
return false;

return true;
}
}

int main()
{
auto primes = std::vector<int>({2});
for (int i = 3 /*2 is already a prime*/; i <= 100; ++i)
if (isPrime(primes, i))
primes.push_back(i);

for (auto prime : primes)
std::cout << prime << ' ';
std::cout << std::endl;
}

但是,由于这道题看起来像是家庭作业,所以不要盲目照搬,先尝试理解这里使用的所有概念。

关于c++ - 无法为整数类型的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38917894/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com