簡體   English   中英

十進制后計數數字

[英]Counting digit after decimal c++

我需要從用戶那里獲得一個雙號。 然后,我需要計算小數點后的位數。 我有另一個想法,我可以將小數部分更改為整數。

例如,如果用戶輸入234.444,則使用此方法,我將從該值中分離出0.444

double usereneteredvalue=234.444;
int value2=userenteredvalue;
double decimalvalue=userenteredvalue-value2;

但是然后我需要將0.444轉換為444,這是我做不到的,因為我不知道十進制后用戶輸入了多少個值。 誰能給我個主意?

將用戶輸入輸入字符串,如下所示:

std::string string;
std::cin >> string;

然后

std::istringstream s(string);
int before, after;
char point;
s >> before >> point >> after;

有一個在你的電話號碼after現在。


編輯:確定更好的解決方案后,使用數字來確定位數

int number_of_digits = string.size() - string.find_last_of('.');

“使用double精度輸入”的問題在於, double精度不會在該點之后存儲用戶定義的位數。 換句話說,您的234.444實際上可能類似於234.4440000000001234.443999999999999

您已經有了一個很棒的C ++風格的解決方案 ,但是從此注釋看來,您似乎不喜歡字符串。

如果您真的不想使用字符串,它將非常難看。 這將在大多數時間*起作用:

//Chop the left side of the decimal off, leaving only the right side
double chop_integer(double d) {
    return d - static_cast<int>(d);
}

...

double some_value;
//We don't really care about the integer part, since we're counting decimals,
// so just chop it off to start
some_value = chop_integer(some_value);

int num_after_dec = 0; //initialize counter
//some_value != 0 won't work since it's a double, so check if it's *close* to 0
while(abs(some_value) > 0.000000001) {
    num_after_dec++;
    //Move decimal right a digit and re-chop the left side
    some_value *= 10;
    some_value = chop_integer(some_value);
}

std::cout << num_after_dec << std::endl;

*雙打根本無法准確存儲某些數字,因此,諸如.111類的操作將失敗

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM