我正在嘗試向我的程式提供資訊,它是否應該列印空間。我正在處理素數分解。
0
1
2 2
3 3
4 2 2// I dont wanna print space at the end
5 5
6 2 3 //but between two nums or more I want space to be added
7 7
8 2 2 2
9 3 3
10 2 5
11 11
12 2 2 3
13 13
我的代碼看起來像這樣,最后的列印空間(這不是我想要的)
void function(int given_limit)
{
int current_num = 2;
while (given_limit > 1)
{
if (given_limit % current_num == 0)
{
if (current_num == 2)
{
printf("%d ", current_num);
}
else if (current_num == 3)
{
printf("%d ", current_num);
}
else if (current_num == 5)
{
printf("%d ", current_num);
}
else if (current_num == 7)
{
printf("%d ", current_num);
}
else
{
printf("%d ", current_num);
}
given_limit /= current_num;
}
else
current_num ;
}
printf("\n");
}
在 main() 我這樣稱呼它:
int main()
{
int given_limit = 13;
for (int i = 0; i <= given_limit; i )
{
printf("%d\t\t", i);
function(i);
}
}
我將不勝感激任何提示和幫助。其中一個想法可能是將其存盤在陣列中。
uj5u.com熱心網友回復:
我用星號替換了空格以獲得更好的可見性,并洗掉了多余的 if 元素。然后我引入了一個標志,它指示它是第一個因素的輸出還是后一個因素的輸出。在后面的每一個前面,我們都放了空格(或星號)。
#include <stdio.h>
#include <stdbool.h>
void function(int given_limit)
{
bool is_first_factor = true;
int current_num = 2;
while (given_limit > 1)
{
if (given_limit % current_num == 0)
{
if (is_first_factor) {
is_first_factor = false; // not first anymore
// print nothing
} else {
printf("*"); // between two factors
}
printf("%d", current_num);
given_limit /= current_num;
}
else
current_num ;
}
printf("\n");
}
int main(int argc, char **argv)
{
int given_limit = 13;
for (int i = 0; i <= given_limit; i )
{
printf("%d\t\t", i);
function(i);
}
}
$ gcc spacing.c
$ ./a.out
0
1
2 2
3 3
4 2*2
5 5
6 2*3
7 7
8 2*2*2
9 3*3
10 2*5
11 11
12 2*2*3
13 13
$
uj5u.com熱心網友回復:
如上所述,將空格字符移動到每個素因子的前面,然后對齊輸出以將初始起始空格字符考慮在內。
這個例子也跳過了不必要的因素。
/* primefactors.c
*/
#include <stdio.h>
void primeFactors(int number)
{
printf(" - ", number);
// only test factors <= sqrt(number)
// skip even factors > 2
int factor = 2;
while (factor <= number / factor) {
if (number % factor == 0) {
printf(" %d", factor);
number /= factor;
}
else if (factor == 2){
factor = 3;
}
else {
factor = 2;
}
}
// at this point number equals the greatest prime factor
printf(" %d\n", number);
}
int main (void)
{
int max = 45;
printf("\nnumber prime factors\n");
printf("------ -------------\n");
// skip 0 and 1 which have no prime factors
printf(" -\n", 0);
printf(" -\n", 1);
for (int i = 2; i <= max; i) {
primeFactors(i);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470683.html
