所以我是 C 的新手,并且一直在做一些練習,嵌套回圈對我來說往往更難。這個關于在兩個用戶輸入數字之間找到一個強數字的新問題讓我感到困惑。本質上,強數是一個數字,其單個數字的階乘加起來就是該數字。例如 145 = 1! 4! 5!= 1 24 120。
我的問題是,在我輸入這兩個數字后,絕對沒有任何反應。我正在嘗試列印一個范圍內的所有強數字。
我一直在嘗試將代碼分段分解,并添加注釋以使我自己和其他人更容易理解。
我正在使用以下函式來查找強數字, int main() 僅具有用戶輸入陳述句:
void strongno(int num1, int num2)
{
// num1 and num2 are from user input in the in main() function
int tot = 0; // to store the total number from each digits factorials
for(int i = num1; i < num2; i )
//getting each individual number in the range, say i = 145
{
while(i)
{
int rem, fact = 1;
rem = i % 10;// I am using this to get each digit alone, so first we get 5
for(int j = 1; j <= rem; j )
{
fact = fact * j;
//the fact will give us the factorial of 5 = 120
}
tot = tot fact; //tot will add all of the factorials of each remainder
// while the number is not 0, so for now it is 120
i = i / 10; // this will give us 14, and the cycle will repeat
}
// Once we have our total, we will compare the actual number i
// to our calculated total. If it matches, it is a strong number
if(tot == i)
{
printf("Strong Number: %d\n", i);
}
else
{
continue;
}
}
}
我覺得主要問題可能在于我實際放置 if 陳述句或其他東西的位置,但是我嘗試安排它但無濟于事。這些回圈對我來說很有意義,它們是如何互動的等等。我試圖不看這個問題的解決方案,因為這永遠不會有幫助,并且更愿意使用我擁有的代碼進行指導,以制定適當的解決方案。任何事情都值得贊賞。
uj5u.com熱心網友回復:
對于初學者來說,最好使用無符號型別unsigned int而不是有符號型別的引數來宣告函式int
void strongno( unsigned int num1, unsigned int num2);
否則,您將遇到負數問題。
使用這個 while 回圈
while(i)
沒有意義,因為它改變i了前面 for 回圈中使用的變數。您需要使用一些中間變數來分配 i 的值。
例如
for( ; num1 < num2; num1 )
//getting each individual number in the range, say i = 145
{
unsigned int i = num1;
//...
此外,該變數tot應在外部 for 回圈內的使用位置宣告和初始化。
for( ; num1 < num2; num1 )
//getting each individual number in the range, say i = 145
{
unsigned int i = num1;
unsigned int tot = 0; // to store the total number from each digits factorials
//...
還有這個 else 宣告
else
{
continue;
}
只是多余的。去掉它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/516681.html
上一篇:pthread_cleanup_push和pthread_cleanup_pop的使用
下一篇:char[]大小未計算在內
