0

how to write an algorithm that converts deceimal to binary, using mod , div and an array to display the answer

3
Contributors
6
Replies
38
Views
3 Years
Discussion Span
Last Post by tinstaafl
0

Here's a simple function that uses pow and outputs a char array(string). Basically it checks if the value is greater than or equal to 2 raised to the power of the loop counter. If so set the character at the opposite end of the char array to 1 and decrement the value by 2 raised to the power of the loop counter. This is set for 8 bits but that can easily be changed.

string ToBinary(int input)
{
    char output[9] = "00000000";
    for(int i= 7; i >= 0; i--)
    {
        if(input >= pow(2.0,i))
        {
            output[7-i] = '1';
            input -= pow(2.0,i);
        }

    }
    return output;
}
0
// converting.cpp : main project file.

#include "stdafx.h"


 #include <iostream>

    using namespace Std;

    int main()

        int array[x] =0;
        int  Deci=0;
         cout<<"enter number";
        cin>>Deci;
        while (Deci!=0)
        {
            array[x] =Deci\2;
            Deci=Deci/2;
        }
            cout<<"results:"<< array[x];
        system("pause");
        return 0;
    }
0

its not doing not working, and the program its telling that cout is undeclared

0

You've got to pay more attention to Intellisense when you're writing your code.

No opening brace for main
A capital 'S' to spell 'std'
'x' is undeclared
array[x] =Deci\2; uses a reverse slash instead of a a modulus sign, array[x] =Deci%2;

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.