在 C++ 中使用 long 和数组
我一直在开发一个将数字转换为二进制的程序。正如您可以在此处看到我的程序,我编写的程序可以比传统的二进制代码缩放更大的数字,例如大于 255 的数字需要 2 行(16 位)。但是,更大的数字需要 long 而不是 int,但这似乎效果不佳,会产生诸如 这个。有人介意帮我把程序改成长期使用吗?或者是否需要对代码进行根本性的更改而不是进行一些小的编辑?
#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char **argv)
{
int j=0;
int c=8;
long a = 1;
int i=1;
cin >> a;
while (a >= (pow(2,c))) {
c = c+8;
i++;
}
long block[i*8];
for (long tw;tw<(i*8);tw++)
{
block[tw] = 0;
}
j=((i*8)-1);
long b = 0;
while (j != -1)
{
if (b+(pow(2,j))<=a)
{
block[j]=1;
b=b+(pow(2,j));
}
j--;
}
long q=0;
cout << endl;
int y=1;
long z = 0;
for (y;y<=i;y++) {
for (z;z<8;z++) {
cout << block[z+q];
}
cout << endl;
z = 0;
q = q + (8*y);
}
}
I've been working on a program that converts numbers into binary. As you can see my program here, I've written so that it can scale for larger numbers then a traditional binary code, such as 2 lines (16-bits) for numbers bigger then 255. However, going larger requires long instead of int, but that doesn't seem to be playing well, producing output such as this. Would anyone mind helping me change the program to use long? Or would it require a fundamental change in the code instead of some minor edits?
#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char **argv)
{
int j=0;
int c=8;
long a = 1;
int i=1;
cin >> a;
while (a >= (pow(2,c))) {
c = c+8;
i++;
}
long block[i*8];
for (long tw;tw<(i*8);tw++)
{
block[tw] = 0;
}
j=((i*8)-1);
long b = 0;
while (j != -1)
{
if (b+(pow(2,j))<=a)
{
block[j]=1;
b=b+(pow(2,j));
}
j--;
}
long q=0;
cout << endl;
int y=1;
long z = 0;
for (y;y<=i;y++) {
for (z;z<8;z++) {
cout << block[z+q];
}
cout << endl;
z = 0;
q = q + (8*y);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使代码变得比需要的复杂得多。这将以二进制形式打印出单个 32 位整数:
如果您想按范围将其阻止以使其更易于阅读,您只需将范围放在循环上(或将其移动到采用范围的函数) 。
You are making your code far more complicated than it needs to be. This will print out a single 32-bit integer in binary:
If you want to block it off by ranges to make it easier to read, you simply need to place range on the loop (or move it to a function that takes a range).
为什么不做一些像这样简单的事情呢?您可以将中间位存储在数组或字符串中,而不是使用 cout。
Why not something simple like this? You could store the intermediate bits in an array or a string instead of using cout.
为了更灵活一点,这里有另一种使用模板的方法。由于扩展问题,带有签名类型的模板实例被故意省略。
For a bit more flexibly, here's another way to do it with templates. Template instantiations with signed types are omitted intentionally due to extension issues.