仅使用基础将十进制转换为二进制

时间:2011-10-21 16:32:02

标签: c++

我必须编写一个程序,将(1.0 - 99.99)之间的十进制数转换为二进制数。我的老师说我们目前只能使用我们在课堂上学到的东西,包括:循环,输入/输出文件,字符串,if / else,cmath和用户定义的函数。我开始编程如何在取小数之前先将整数转换为二进制。我能够计算二进制值,但我以相反的顺序吐出我的二进制文件。所以我的老师说要将余数(例如:位值)发送到文件并将其作为字符串读取。我现在是哪一个。还是有同样的问题。如何以相反的顺序从字符串中打印这些值? 到目前为止我的尝试:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;



int main()
{
int number;
int remainder;
string bitValues;
ofstream outFile;
ifstream inFile;

//inFile.open("C:\\Users\\David\\Desktop\\BinaryIn.txt"); // pay no mind to this.
outFile.open("C:\\Users\\David\\Desktop\\BinaryOut.txt");

cout << "Enter a integer to be converted to binary: ";
cin >> number;

while(number != 0)
{
    remainder = number % 2; 
    outFile << remainder << " "; // I send it to the outFile
    number /= 2;
}
outFile.close(); // I close because I need to read from it now.

inFile.open("C:\\Users\\David\\Desktop\\BinaryOut.txt"); //I did this so I can read      from the same outFile

getline(inFile, bitValues); //had to look up getline(), was not covered in class
// I just came up with this idea, is this Valid??????????

    int posisiton = 10;
while(posisiton >= 0)
{
    cout << bitValues[posisiton]; // I ever done something like this but It worked!
    posisiton--;
}


int pause;
cin >> pause;

return 0;
}

2 个答案:

答案 0 :(得分:1)

你知道如何编写递归函数吗?通过在输出余数之前进行递归调用(而不是之后),您将获得所需的效果。

答案 1 :(得分:0)

1)忘记文件(我不知道这会有什么帮助。也许你误解了老师)。只需编写一个简单的函数来反转字符串。

for(int i=0; i<bitValues.length()/2; ++i) {
    char t = bitValues[i];
    bitValues[i] = bitValues[bitValues.length()-1-i];
    bitValues[str.length()-1-i] = t;
}

2)或者不使用模数,而是使用一个标志来第一次按顺序获取位。这不是代码,因为它与您的作业更直接相关,而不是简单的字符串反转。

resize the string to be big enough to hold all the bits
set a mask to have a 1 in the 31st position
for each position in the string
    use `&` with the mask to find if it's a one or zero
    set the character depending on the bit
    shift the mask right one.