我是編程新手,我必須以五行的形式顯示作為此代碼乘積的所有質數。經過太多小時的嘗試在網上找到一些東西后,這就是我想出的。這樣,即使是素數也不會顯示在最后;一路只有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;
}
uj5u.com熱心網友回復:
您的輸出邏輯嚴重過度復雜。只需在執行輸出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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336425.html
下一篇:簡單回圈python“for”
