所以我正在尝试制作一个打印出所有完美整数高达10000的程序,我已经能够让我的程序能够做到这一点,但我似乎无法正确安排打印出来;我想让它显示如下:
6:1 2 3
28:1 2 4 7 14
496:1 2 4 8 16 31 62 124 248
8128:1 2 4 8 16 32 64 127 254 508 1016 2032 4064
但我现在正在接受这个:
8128:4064
8128:2032
8128:1016
8128:508
8128:254
8128:127
8128:64
8128:32
8128:16
8128:8
8128:4
8128:2
8128:1
我已经尝试了我能想到的一切,但似乎无法做到正确:C,
(ps:它为每个完美整数垂直显示输出:c)请帮助
#include <iostream>
#include <string>
using namespace std;
void perfect(int number)
{
int DivTotal = 0, Div;
//string
for (int halfNum = number / 2; halfNum >= 1; halfNum--)
{
Div = number % halfNum;
if (Div == 0)
DivTotal += halfNum;
}
if (DivTotal == number)
{
for (int halfNum = number / 2; halfNum >= 1; halfNum--)
{
Div = number % halfNum;
if (Div == 0)
cout<< number << ":"<< halfNum<<endl;
//cout<<endl;
}
}
}
int main()
{
cout << "Perfect numbers between 1 and 10000 are:" << endl;
for (int count = 1; count <= 10000; count++)
{
perfect(count);
// cout << perfect<< ":" << endl;
}
system("Pause");
}
答案 0 :(得分:1)
迄今为止的微调变体给出答案:
if (DivTotal == number)
{
// needs to be moved out of loop for not being printed with every number
// additionally, 1 is always a divisor, so we can add it right here:
std::cout << number << ": 1";
for(int i = 2; i * i <= number; ++i) // counting up to have order right!
//^^^^^ until sqrt only...
{
if(number % i == 0)
std::cout << ", " << i;
//^ with or without comma...
}
std::cout << std::endl;
}
答案 1 :(得分:0)
我希望这有助于
if (DivTotal == number)
{
char toPrint[100];
char toAdd[10];
sprintf(toPrint,"%d:",number);
for (int halfNum = number / 2; halfNum >= 1; halfNum--)
{
Div = number % halfNum;
if (Div == 0)
{
sprintf(toAdd," %d ",halfNum);
strcat(toPrint,toAdd);
}
}
cout<< toPrint<<endl;
//cout<<endl;
}
使用sprintf和strcat remeber包含stdio.h