一定数量的模数并在分部声明中打印答案

时间:2014-07-27 08:18:40

标签: modulo

#include <iostream>

using namespace std;
int main(){
    int num;
    cout<<"Number: ";
    cin>>num;
    int answer;
    answer = num%2;
    cout<<"\n"<<answer;
}

我有在我的部门声明中打印答案的问题。

2 个答案:

答案 0 :(得分:2)

修复递归函数,在展开时显示输出,即在递归调用之后

void DecimalToBinary(int n){
    int r;
    if (n != 0) 
    {
        r = n%2;
        DecimalToBinary(n/2); // recurse
        cout <<r; // Then simple print r, as its either 0 or 1
    }
   // Your else if is not stopping the recursion and its not required
}

答案 1 :(得分:0)

尝试使用以下功能代替您的< - p>

void DecimalToBinary(int n){

    static int i=31; //(i=31 for 32 bit integers)
    if(i>=0){
            if (n&(1<<i--)){    //if the answer in r is 1 it will print 1
                    cout<<"1";
            }
            else{
                    cout<<"0";   //if the answer in r is 0 it will print 0
            }
            DecimalToBinary(n);
    }
}