c++ - 如何以五个数字的行显示输出?
问题描述
我是编程新手,我必须以五行显示作为此代码乘积的所有质数。经过太多小时试图在网上找到一些东西,这就是我想出的。这样,最后连质数都不会显示;一路只有1s。我很高兴知道我做错了什么或者我可以改变什么。
#include <iomanip>
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main() {
int n { 0 };
cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl;
cin >> n;
vector<bool> cygnus(n + 1);
for (int m = 0; m <= n; m++) {
cygnus[m]=true;
}
for (int j = 2; j < n; j++) {
if (cygnus[j] == true) {
for (int i = j + 1; i <= n; i++) {
if (i % j == 0) {
cygnus[i] = false;
}
}
}
}
int s = 0;
for (auto value : cygnus) {
if (value == true && s > 0) {
for (int counter = s; counter++; ) {
if (counter % 5 == 0) {
cout << setw(3) << s << " \n ";
}
if (counter % 5 != 0) {
cout << setw(3) << s << " ";
}
}
}
s++;
}
cout << endl;
return 0;
}
解决方案
您正在严重过度复杂化您的输出逻辑。只需在执行输出counter
的循环外部声明一个变量(并初始化为零)for
,然后每次打印一个数字时,将其递增。当它达到 5 的值时,打印一个换行符并将其重置为零。
其他几点:
STL 容器(如
std::vector
)使用类型size_t
(不是int
)作为它们的大小和索引。int
在下面的代码中,我已将您的所有变量都更改为这种类型;幸运的是,这不会影响您的算法。请注意,1 不是质数。
这是您的代码的重新处理版本:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
size_t n{ 0 };
cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl;
cin >> n;
vector<bool>cygnus(n + 1);
for (size_t m = 0; m <= n; m++) {
cygnus[m] = true;
}
for (size_t j = 2; j < n; j++) {
if (cygnus[j] == true) {
for (size_t i = j + 1; i <= n; i++) {
if (i % j == 0) {
cygnus[i] = false;
}
}
}
}
size_t s = 0;
size_t counter = 0;
for (auto value : cygnus) {
if (value == true && s > 1) { // Note that 1 is NOT a prime number
cout << setw(3) << s << " ";
if (++counter == 5) {
cout << "\n ";
counter = 0;
}
}
s++;
}
if (counter != 0) cout << "\n "; // Add newline for any partial last line.
cout << endl;
return 0;
}
推荐阅读
- python - 如何使用条件将 A 列中的值替换为 B 列
- react-native - 视频通话期间的问题(opentok-react-native)
- python - Microsoft 是否提供任何 API 来访问启用宏的 Excel 文件
- python - 从 Django 中的两个视图发送回表单
- java - 如何使用 springdoc-openapi 使可选的 OpenAPI 参数为空?
- spring-security - 为什么我的 Spring http 会话会在几秒钟内被破坏?
- redirect - 与来自 IIS 网站的 Plesk 重定向通信的问题
- reactjs - Ant设计Cascader组件中如何反转选项
- python - 合并两个带有共同值提示的数据框
- html - 在 img type="button" 上添加文本