022給定一個字串類型(string)表示的小數,列印出它的二進位表示(keep it up),022string

來源:互聯網
上載者:User

022給定一個字串類型(string)表示的小數,列印出它的二進位表示(keep it up),022string
給定一個字串類型(string)表示的小數,列印出它的二進位表示。
這個題注意字串的合法性。
不過下面的代碼沒有處理那種無限迴圈的小數,

當出現無限迴圈小數時,while(other>0)可能永久為true

代碼:

#include <iostream>#include <string>std::string to_binary_string(const std::string& vNumStr){std::string::size_type Pos = vNumStr.find('.');std::string IntPart = vNumStr.substr(0, Pos);std::string OtherPart = vNumStr.substr(Pos, vNumStr.length()-Pos);if (IntPart != ""){int Num = atoi(IntPart.c_str());IntPart = "";while (Num){if (Num&1) IntPart = "1" + IntPart;else IntPart = "0" + IntPart;Num >>= 1;}}    if (OtherPart.size() > 1){int Other = atof(OtherPart.c_str());OtherPart = "";while (Other>0){Other *= 2;if (Other>=1){OtherPart += "1";Other -= 1;}else{OtherPart += "0";}}}return OtherPart.size() > 1 ? IntPart + OtherPart : IntPart;}



小數怎以二進位表示?

可以這樣:首先將一個小數如:235.725的小數部分取出,即:0.725,將其乘以進位數二進位就乘以2後得到1。45,取其整數部分1為二進位小數的第一項(十分位),在將小數部分0。45乘2得0。9,取其整數部分為二進位小數的第二位(百分位)0,在將其小數部分0。9乘2,得1。8,取其整數部分為二進位小數的第三位(千分位)1,取其小數部分0。8再乘2……以此類推,直到值為0或形成迴圈小數則停止。
 
怎用二進位表示一個小數

比如說5.6

整數部分5用2進位為101

小數部分0.6
有這樣一個公式: *2 如果<1就為0,基數=基數;大於1,就為1,基數=基數-1

0.6*2=1.2>0 那麼就為1 基數=1.2-1=0.2

0.2*2=0.4<0 那麼就為0,基數=0.4

0.4*2=0.8<0,那麼就為0,基數=0.8

0.8*2=1.6>0 那麼就為1,基數為1.6-1=0.6
:
:
:
:
所以5.6可以表示為:101.1001
想往下面再乘,就更精確了
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.