Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c++ - Decimal to binary without arrays and binary-operators (like "&")

I have to do a task for the university to write a program that converts a decimal number into binary. As I am only in a preliminary course of computer science, there were no arrays or bitwise operators (like '&') introduced yet. The program needs to be written using basic operators (+,-,*,%) and (if-else,for) only. My approach is the following, but I always get the inverted value. So instead of 1100, 0011.

#include <iostream>
int main()
{
   int n,a;
   std::cin >> n;
   
   for (int i=n; n>0; --i) {
       
     a = n%2;
     std::cout << a;
     n = n/2;
   
   }

   return 0;
}

is there a way to solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your current code checks for presence of the binary value from LSB to MSB, and prints in that order. One way to approach the issue would be to instead check from MSB to LSB.

#include <iostream>
int main(){
  int n, a=1;
  std::cin >> n;

  while(2*a <= n)
    a *= 2;                                                                                                               
  while(a > 0){
    if (n >= a){
      std::cout << 1;
      n -= a;
    } else {
      std::cout << 0;
    }
    a /= 2;
  }
  std::cout << std::endl;
  return 0;
}

This isn't a great way to do this, and I recommend improving it or finding alternatives as an exercise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...