2014-10-04 26 views
-2

我做節目,總結一個數字,看看這個程序:如何在一個數字中計算總和?

#include<iostream> 
using namespace std; 

int main(){ 

    int i, j; 
    int sum=1; 
    cout<<"Enter your sum: "<<endl; 
    cin>>i; 

    while(i>0){ 
     j=i%10; 
     sum=sum+j; 
     i=i/10; 

    } 
    cout<<"Sum: "<<sum; 
    cout<<endl; 
} 

所以,當我鍵入如25輸出它會給我作爲輸出7

但是我想在每個數字的一​​個數字中,讓我們說,因爲我輸入147。它給了我一個輸出10,但我想要1作爲輸出。

我知道它可以完成此操作:

while(i>0){ 
     j=i%10; 
     sum=sum+j; 
     i=i/10; 

    } 
    cout<<"Sum: "<<sum/10; 

和它肯定會給我一個輸出1

但是當我輸入一個數字185它給了我一個輸出1 ..但是我想要數字的總和。

我想要的程序在其中如果鍵入185

輸出必須假設是因爲

1+8+5=14 
1+4=5 

和輸出必須5 ..所以,請大家幫我解決這種問題。

+3

您只需要重複該過程,直到結果爲單個數字。重複 - >你需要一個(n外部)循環。 – 2014-10-04 10:11:48

+0

@KarolyHorvath;不需要使用外部循環。 – haccks 2014-10-04 10:28:24

回答

1

你可以試試這個:

while(i>0){ 
    j=i%10; 
    sum=sum+j; 
    i=i/10; 
    if (i == 0 && sum >= 10) // if all the digits of previous number is processed and sum is not a single digit 
    { 
     i = sum; 
     sum = 0; 
    } 
} 

注意,沒有嵌套循環!

不要忘了將sum初始化爲0而不是1

5

你所描述的稱爲digital root。因爲185 = 9*20 + 5而0由9.

unsigned digitalRoot(unsigned i) 
{ 
    return 1 + (i-1)%9; // if i%9==0, (i-1)%9==8 and adding 1 yields 9 
} 

digitalRoot(185)取代是5 - 有趣的是,它可以通過由9分割時簡單地確定計算的餘數。

2

我鍵入25輸出它會給我作爲一個輸出7.

不,它實際上是8demo)。問題是,您將sum初始化爲1而不是0

至於製作和一個單一的數字去,加入另一個循環到你的程序:

for (;;) { // Loop until the break is reached 
    while(i>0){ 
     j=i%10; 
     sum=sum+j; 
     i=i/10; 
    } 
    if (sum < 10) break; // It's single digit 
    i = sum; 
    sum = 0; 
} 
+0

@rajivmishra這取決於你。對我來說,兩個循環以更清晰的方式向讀者展示了代碼背後的意圖,因爲如果您想用鉛筆和紙張來運行,您基本上會記下算法的作用。對我來說,在代碼中將兩個邏輯循環壓縮到一個循環中是不對的,但這只是我的看法。 – dasblinkenlight 2014-10-04 10:37:53

+0

雅你也是對的.. – 2014-10-04 10:47:00

+0

我也很感謝你的回答.. – 2014-10-04 10:47:22

0
import java.util.*; 
public class SingleDigit 
{ 
    public static void main(String[] args) 
    { 
     int number = 0, temp = 0, result = 0; 
     Scanner inp = new Scanner(System.in); 
     System.out.print("Enter the Number :"); 
     number = inp.nextInt(); 
     temp = number; 
     while(temp>0) 
     { 
      result = result + (temp%10); 
      temp = temp/10; 
      if(result > 9) 
       result = (result % 10)+(result/10); 
     } 
     System.out.println("Single Digit Number for the Number "+number+" is :" result); 
     System.out.println("Thank You KING...."); 
    } 
} 
+0

這個問題被標記爲C++ – 2016-10-12 00:59:55