-3

C ++では、2つの2進数を読み取って加算の結果を出力し、各数値が4ビットの2進数を読み取る関数を使用し、(バイナリ1、バイナリ2)を追加する関数を使用するプログラムを作成するにはどうすればよいですか? !

このプログラムを見つけましたが、配列を使用したくありません。関数のみが必要です。

#include <iostream>
#include <string>
using namespace std;

int main()
{
int a[4];
int b[4];
int carry=0;
int result[5];


a[0]=1;
a[1]=0;
a[2]=0;
a[3]=1;

b[0]=1;
b[1]=1;
b[2]=1;
b[3]=1;

for(int i=0; i<4; i++)
{

    if(a[i]+b[i]+carry==3)
    {
    result[i]=1;
    carry=1;
    }
    if(a[i]+b[i]+carry==2)
    {
    result[i]=0;
    carry=1;
    }
    if(a[i]+b[i]+carry==1)
    {
    result[i]=1;
    carry=0;
    }
    if(a[i]+b[i]+carry==0)
    {
    result[i]=0;
    carry=0;
    }


}
result[4]=carry;
for(int j=4; j>=0; j--)
{
    cout<<result[j];

}
cout<<endl;

    return 0;
}
4

1 に答える 1

0

残念ながら、-familyocthexdecをサポートしていますが、バイナリ数値表現はサポートしていません。std::iostreamscanf

基本的に、 と を使用strtolitoaます。後者は (ANSI に準拠していないため) gcc では使用できないため、 の実装のスニペットを追加しましたitoa

#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

/*CREDIT goes to: http://www.jb.man.ac.uk/~slowe/cpp/itoa.html*/
// you should not need this function if compiled smoothly without it
//  ( if you're on Microsoft Visual Studio, you don't need this function
char* itoa(int val, int base){  
    static char buf[33] = {0};  
    int i = 30; 
    for(; val && i ; --i, val /= base)  
        buf[i] = "0123456789abcdef"[val % base];    
    return &buf[i+1];   
}

int main(){
    int a,b;
    char p[100];
    printf("enter your first number:\n");
    scanf("%s",p);
    a = strtol(p,NULL,2);
    printf("enter your second number:\n");
    scanf("%s",p);    
    b = strtol(p,NULL,2);
    printf( itoa( a+b , 2 ) );
    printf("\n");
}
于 2013-05-10T13:11:29.627 に答える