我想做一個程序,允許用戶輸入一個正整數,並且程序將輸出每個數字加在一起的總和。例如,如果用戶輸入54
,程序將輸出9
。出於某種原因,該計劃正在輸出巨大的數字。當輸入爲54
時,輸出將讀取類似5165451
或2191235
的內容。我是新的C++編程,但我沒有看到一個單一的東西錯這個代碼..爲什麼我通過這個程序獲得大量的輸出?
//This program takes a positive integer
//from the user, and adds all the digits
//of the number together.
#include <stdio.h>
int main() {
system("clear");
int given, add, hold, i;
printf("Enter a positive integer (up to 10 digits): ");
scanf("%d", &given); //User input
for (i = 0; i < 10; i++) { //Loop to add digits
hold = (given % 10);
given = (given/10);
add = (add + hold);
}
printf("Sum of the digits is %d\n", add); //Output
}
你沒有初始化'add'。 – cnicutar
這可能是我的,但我從來沒有聽說過「明確」是一個命令。也許你正在那裏尋找'cls'。 – chris
我的直覺告訴我這是因爲你還沒有將'add'初始化爲0.編輯:哎呦,太慢 –