[英]How I can reduce the decimal numbers after the point and fix a bug that show a lot of words?
[英]How can I use the numbers to the right of a decimal point in a double?
我很抱歉是否已經問過這個問題(我想是因為這是一個非常簡單的問題,而不是因為我沒有嘗試先找到它!)。
我試圖做的是一次構建一個雙數字一字符。 左邊的數字很容易,行num = num * 10 + (c - '0');
/*num being the number built so far and c being the char added*/
但是然后做類似的事情
num = (double)((int)num) + ( (num%1)*10 + (c - '0') )/decDigits; //decDigits is the number of digits(including the new one) to the right of the decimal point
將無法正常工作,因為顯然您不能在double上使用%運算符。
實現上述目標的正確方法是什么?
您是否要將雙精度型轉換為字符串,或將字符串轉換為雙精度型? 看起來就像后者,在這種情況下,我認為您根本不應該使用%
運算符。 從0.1
開始,將每個數字的值乘以適合其位置的值。
不過,用C解釋起來更容易:
char c;
double result = 0.0;
/* The part before the decimal place */
while ((c = *s++) && c != '.') {
result = result * 10.0 + (c - '0');
}
/* The part after the decimal place */
if (c == '.') {
double m = 0.1;
s++;
while ((c = *s++)) {
result += m * (c - '0');
m *= 0.1;
}
}
沒有為浮點定義模運算符。 如果你要使用num%1
提取的小數部分num
,則應該嘗試是這樣的:
double num_dec = num - floor(num);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.