2013-06-25 103 views
0

問題:用戶輸入的10位數,需要計算所有數字的總和。將多個數據記錄到一個變量中

我想鍵入變量「int a [10] = {}」但它不起作用,我可以在它寫幾個結果嗎?

請寫下示例代碼。

+0

你的意思是'10位數的數字,是嗎?如果是,它是一個「int」值,你不能直接在數組中存儲單個數字。 – Federico

回答

0

你沒有指定你正在使用哪種語言,所以我回答你,假設你用java編碼。

爲了你問什麼,你必須這樣做:

int number = 454685; // = an example number 
    int[] arr = new int [6]; // array of int, 6 = digits of the number 
    int i = 0; // counter 
    while (number > 0) { 
     arr[i] = number % 10; //stores in arr[i] the last digit 
     i++; //increment counter 
     number = number/10; //divides the number per 10 to cancel the last digit (already stored in arr[i]) 
    } 
    int sum = 0; //declares the sum variable 
    i = 0; //reset counter 
    do{ 
     sum = sum + arr[i]; 
     i++; 
    }while(i < arr.length); //this loop calculates the sum 
    System.out.println(sum); //prints the sum of the digits 

給你。

+0

語言Objective-C – user2520114

+0

@ user2520114然後看看這個問題http://stackoverflow.com/questions/2303125/extracting-digits-from-integer-and-decimal-parts-of-a-double和這個http: //stackoverflow.com/questions/15728816/how-to-split-integer-into-component-digits – Federico

相關問題