我不是想要求你們幫我做作業,因爲我已經做了大量的研究,也嘗試自己編程,但仍然遇到問題,我覺得到目前爲止,我知道問題出在哪裏,但仍然沒有解決方案可以找出由我:返回給定數字之前的所有素數(家庭作業C++)
守則
#include <iostream>
#include <string>
#include <cmath>
int main(void)
{
using namespace std;
int num;
int max;
string answer = "";
cin >> num;
for(int i = 2 ; i < num ; i++)
{
max = sqrt(i);
if(max < 2) // This must be done beacuse sqrt(2) and sqrt(3)
{ // is 1 which will make it become nonprime.
answer += i;
answer += ' ';
continue;
}
for(int j = 2 ; j <= max ; j++) // Trial division ,divide each by integer
{ // more than 1 and less than sqrt(oftheinteger)
if(i % j == 0)
break;
else if(j == max)
{
answer += i + " ";
answer += ' ';
}
}
}
cout <<"The answer is " << answer ;
return 0;
}
問題
1)本程序w生病提示輸入用戶號碼並返回所有素數(例如,如果用戶輸入9:則答案爲2,3,5,7)。
2.)我認爲錯誤的部分是字符串和整數連接,直到現在我仍然拼圖如何在C++中連接字符串和整數(以前的Javascript程序員,所以我習慣於使用+
作爲string-int concat操作符)
3.)除了上面提到的問題之外,到目前爲止我已經通過代碼並發現沒有其他問題存在。如果任何專家設法找到任何東西,請介意指出它以啓發我?
4.)如果在編碼或算法方面有任何錯誤,或者我做了什麼,請不要猶豫,指出它,我願意學習。
謝謝你花時間閱讀我的問題
究竟是什麼錯誤?它打印出什麼? – talnicolas
它給你什麼,而不是你期望的答案? – rcollyer
它需要把所有東西放在一個字符串中嗎?發現每個素數時打印會更容易。 – madth3