我试图迭代一个数组,并确定每个数字是否为素数。
这是我的代码:
constants.h
#pragma once
#ifndef CONSTANTS_H
namespace constants {
constexpr int randomOne[10] = { 1,3,5,7,9,12,13,15,18,23 };
}
#endif // !CONSTANTS_Hmain.cpp
#include <iostream>
#include "constants.h"
int main() {
//Check a number in an array to see if it is prime or not
int count = 0;
for (int i = 1; i <= 10; ++i) {
//std::cout << constants::randomOne[i] << '\n';
//Uncomment the line above and the console prints each number in the array
//To check how many times the number in the array has been divided between 1 and itself we take count and increment it each time it is divided.
//If the count is greater than two (2) we know the number is not prime.
for (int j = 1; j <= constants::randomOne[i]; ++j)
{
if(constants::randomOne[i] % j == 0)
++count;
}
//The above code should divide the number in the array by one and increment up by one all the way up to the number.
//If it returns a value higher than two than the number is not prime.
//Example: Say the number in the array is 4 so - 4 % 1 = 0, 4 % 2 = 0, 4 % 3 != 0, 4 % 4 = 0 would increment to three (3) so four is not prime.
if (count == 2)
{
std::cout << constants::randomOne[i] << " is not prime, rather it is a composite number.\n";
}
else
{
std::cout << constants::randomOne[i] << " is prime!!!\n";
}
}
}当我运行代码时,它会返回:
3 is not prime, rather it is a composite number.
5 is prime!!!
7 is prime!!!
9 is prime!!!
12 is prime!!!
13 is prime!!!
15 is prime!!!
18 is prime!!!
23 is prime!!!
1052166324 is prime!!!我完全搞砸了,我哪里出错了?为什么我没有得到正确的素数响应?
编辑感谢大家支持我的“走出指南”的帖子足够长的时间给我一些指点。这些建议都非常有用,特别是使用我的调试器(learncpp.com在如何使用它方面有一些很好的经验)。调试器帮助我可视化我的代码逻辑正在崩溃的地方。另外一个很好的建议是从main中删除一些代码逻辑。我的解决方案可以找到这里
还有(和我的整个问题不太相关,但现在我很好奇),我到底是怎么得到1,052,166,324的?Int持有2,147,483,647,如果它没有签名,如果它是1,073,741,823正数,这比我的控制台说的少21,575,499。此外,数组有10位长,那么为什么它跳过数组前面的1,并将巨大的数字添加到末尾呢?这是编译器特有的问题吗?还是它只是随机地从10个地址加了个内存?
发布于 2021-08-21 01:56:38
除了注释中提到的超出界限的错误,您还可以看到逻辑向后--如果是count==2,那么这个数字不是素数--而您忽略了重置count。
简而言之,您的代码中充满了bug,如果您从一些小的、简单的、完美地工作的东西开始,然后在小的增量中构建,然后在每一步进行测试,您可能会发现这些错误。如果您编写了这么多代码而不对其进行测试,那么您将不可避免地构建一个bug集合。投票结束。
发布于 2021-08-21 01:47:27
请查看此戴夫·普鲁默的github项目 (已退休的MSFT /C++)。这是一个非常酷的比较不同的语言使用一个主要的筛子,所以我相信它会回答你的问题,并演示一个优化的程序。此外,您还可以查看C++如何与其他公共语言进行叠加。(扰流板警报,C++几乎总是获胜)
https://stackoverflow.com/questions/68869485
复制相似问题