Thread: Can someone diagnose the print issue?

  1. #1
    Registered User
    Join Date
    Oct 2018

    Can someone diagnose the print issue?

    Why does the "Binary: " always print "Binary: 0"?

    #include <math.h>
    #include <stdio.h>
    int main(void) {
        int x;
        int y = 0, i = 0;
        int z;
        printf("Enter a binary number: ");
        scanf("%d", &x);
        if (x < 0) {
        while (x > 0) {
            z = x % 10;
            y = y + z * pow(2, i);
            x = x / 10;
        printf("Binary: %d\n", x);
        printf("Decimal: %d\n", y);
        return 0;

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Because the only way for the loop to terminate is when x <= 0, and since x never becomes negative, it means that x is always 0 at the termination of the loop. If you want to retain the original value, you need to save it somewhere before the loop.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Issue with the print of this program
    By Jesse Bettcher in forum C++ Programming
    Replies: 7
    Last Post: 11-18-2014, 07:13 AM
  2. Replies: 15
    Last Post: 06-13-2012, 12:34 PM
  3. fgets and scanf - couldn't diagnose new line bug.
    By sandeep_vr in forum C Programming
    Replies: 2
    Last Post: 02-24-2012, 06:32 PM
  4. C file print Issue in Line feed
    By muni in forum C Programming
    Replies: 3
    Last Post: 04-21-2008, 09:29 AM
  5. Print to file issue
    By jed in forum C++ Programming
    Replies: 2
    Last Post: 10-18-2006, 09:54 PM

Tags for this Thread