我應該得到一個十進制數,分別總結了整個部分的數字,並分別小數部分,如何在C中分別在小數點前後求和?
因此,例如,如果我得到: 1321.0365 輸出應該是:7.14
我米應該這樣做,而不使用數組。 這是我從現在開始嘗試做的,從函數中獲取數字後,首先分離兩個部分,然後將十進制數乘以10,直到數字等於int部分。 然後我試圖將每個部分分開求和,並且在我這樣做之後,除以小數部分,直到數字等於整數。理論上它聽起來應該起作用,但我想我錯過了一些路上的東西。 這是我迄今所做的:
double number;
double sumReal=0;
int wholePart;
int sumWhole=0;
int multiply=1;
number=getDecimalNumber();
wholePart=number;
number-=wholePart;
while(number!=(int)number)
number*=10;
while (number!=0)
{
sumReal+=(int)number%10;
number/=10;
}
while (wholePart!=0)
{
sumWhole+=(int)wholePart%10;
wholePart/=10;
}
while(sumReal!=(int)sumReal)
sumReal/10;
number=wholePart+sumReal;
莫名其妙大部分部件似乎工作,但乘以10的實部總是讓我爲0,並總結實部,並在整數的時候最後也讓我0,這導致我輸出0。
這種情況下'(數字!=(int)的數量)'永遠是正確的,因爲你是因爲精度比較有限,雙整數。所以你會被困在循環中。 – 2014-12-01 21:07:53
請注意,由於「double」中的有界精度(有效數字的數量),嘗試除法和減法直到達到零是沒有意義的。您必須在小數點後面預先定義最大所需的小數位數,以便計算每位數字。 – 2014-12-01 21:20:09
getDecimalNumber如何工作? double可能無法完全按照給定的原樣包含原始輸入數字。 – 2014-12-01 21:28:53