我正在從一個程序讀取命令行中的兩個十進制數字,將它們轉換爲二進制,將它們相加,然後輸出二進制和十進制的和。將函數輸出到int數組中
我做了一個將十進制輸入轉換爲二進制的函數,但現在我無法弄清楚如何將這些值轉換爲int數組。
例如: 輸入:./a.out 3 2
我的函數轉換成3和11 2到10
現在我需要把這些值在int數組的末尾,以便它看起來像這樣:0000000000000000000000000000011和00000000000000000000000000000010
這樣我的邏輯添加二進制數可以正常工作。
這裏是我的嘗試,但它說,它可以從虛空分配INT:
#include <iostream>
#include <cstdlib>
#include <string.h>
using namespace std;
void binary(int);
int main(int argc, char* argv[])
{
if(argc != 3)
{
cerr << "Invalid number of operands" << endl;
return 1;
}
int i;
int arg1 = atoi(argv[1]);
int arg2 = atoi(argv[2]);
int sum = arg1 + arg2;
int a[32];
int b[32];
int c[32];
int carry = 0;
bool print = false;
for(i = 0; i < 32; i++)
{
a[i] = 0;
b[i] = 0;
c[i] = 0;
}
for(i = 31; i >= 0; i--)
{
a[i] = binary(arg1); //PROBLEM AREA
b[i] = binary(arg2); //PROBLEM AREA
}
for(i = 31; i >= 0; i--)
{
if (a[i] == 1 && b[i] == 1 && carry == 0)
{
c[i] = 0;
carry = 1;
}
else if (a[i] == 1 && b[i] == 0 && carry == 0)
{
c[i] = 1;
carry = 0;
}
else if (a[i] == 0 && b[i] == 0 && carry == 0)
{
c[i] = 0;
carry = 0;
}
else if (a[i] == 0 && b[i] == 1 && carry == 0)
{
c[i] = 1;
carry = 0;
}
else if (a[i] == 1 && b[i] == 1 && carry == 1)
{
c[i] = 1;
carry = 1;
}
else if (a[i] == 1 && b[i] == 0 && carry == 1)
{
c[i] = 0;
carry = 1;
}
else if (a[i] == 0 && b[i] == 0 && carry == 1)
{
c[i] = 1;
carry = 0;
}
else if (a[i] == 0 && b[i] == 1 && carry == 1)
{
c[i] = 0;
carry = 1;
}
}
if(carry == '1')
cout << carry;
for (i = 0; i < 32; i++)
{
if (c[i] == 1)
print = true;
if (print)
cout << c[i];
}
cout << " = " << sum;
cout << endl;
return 0;
}
void binary(int number)
{
int remainder;
if(number <= 1)
{
cout << number;
return;
}
remainder = number % 2;
binary(number >> 1);
cout << remainder;
}
任何意見或建議,將不勝感激!
'無效二進制(INT);'返回'void'所以你怎麼能分配'無效'到'int'? 「void」意味着你實際上沒有返回任何東西。怎樣才能將任何東西('void')分配給某個東西('int')? –
好,如果我只是把二進制(arg1)或二進制(arg2)程序將輸出11或10 – Blake
你應該明白,你輸出在屏幕上,不是你的函數返回! – Shahbaz