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

Converting Decimal to binary using only the basics

本文关键字:转换 二进制 十进制 基础知识      更新时间:2023-10-16

我必须写一个程序将(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;
}

你知道怎么写递归函数吗?通过在输出余数之前(而不是之后)执行递归调用,您将获得想要的效果。

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.