仅使用基础知识将十进制转换为二进制
Converting Decimal to binary using only the basics
我必须写一个程序将(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.
相关文章:
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- C++从二进制转换为十进制数
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 如何在 O(n) 中将二进制和转换为二进制
- 我写的 ASCII 到二进制转换器C++向后显示二进制,如何使其正确显示?
- 十进制到二进制转换器 c++
- 在C++中将结构转换和存储为二进制
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- 如何在C ++中将二进制字符串128位转换为十进制字符串?
- 如何将二进制文件头示例代码 (C++/C#) 转换为 Python?
- 二进制 '==':未找到采用 'Enemy' 类型左侧操作数的运算符(或者没有可接受的转换)
- 将二进制转换为十进制,我如何要求用户仅输入二进制
- QTextStream的操作数到二进制的转换无效
- 在c++中读取和转换二进制数据
- c++转换二进制到十进制从字符串输入
- 计算器转换二进制到浮点值-我做错了什么