tags:

views:

301

answers:

6
+2  Q: 

Strange code error

This is regarding the problem which I posted earlier today. I made the program to identify and print the digits of a given number. The program runs fine when I use 1, 2, 4 digits (I made 4 max), but when I input a 3-digit number, it prints the numbers wrong and ends abruptly. Help me out..

#include <stdio.h>
#include <stdlib.h>
#include <digits.h>
int getDigit(long);
int main()
{
  int ctr, digits, dig, multiNo, number;
  printf("Enter the number(4 digits max): ");
  scanf("%d", &number);
  printf("\n");
  digits = getDigit(number);
  if (digits == 1)
     printf("%d\n", number);
  else              
  {
    multiNo = pow(10, (digits-1));
    ctr = 1;
    dig = (number/multiNo);
    printf("%d ", dig);    
    while (ctr < digits)  
    {     
      number %= multiNo;
      multiNo/= 10;
      dig = (number/multiNo);
      printf("%d ", dig);
      ctr++;
    }
  }
  printf("\n\n");
  system("PAUSE");
  return 0;
}

int getDigit(long num)
{
  long divider = 10; 
  int digit, i;
  for (i=1; i<=9; i++)
  {
    digit = (num/divider);
    if (digit == 0)
      break;
    else
      divider *= 10;
  }
  return i;
}

Sorry, I'm using a phone to browse internet, so unable to format..

+2  A: 

Apparently code looks fine. Please check the return value of getDigit(number);.

I just hard coded as digits = 3/*getDigit(number)*/; and the code was printing proper values for 3 digit number.

aJ
+1  A: 

Since I dont have your getDigit() function I just let my version return 3, so I can test a 3 digit number and it works fine. My guess is that your getDigit() is messed up.

You program works just fine.

Magnus Skog
Talk about orange bar of death and exact same answer =/
Magnus Skog
A: 

changing the top of main to:

//  printf("Enter the number(4 digits max): ");
//  scanf("%d", &number);
for(int x=1;x<10000;x++){
 number=x;

and a } at the bottom seems to work for me for any length of number.

Dolphin
A: 

It works for me but you need to clarify the type you are passing for the first parameter to 'pow' i.e.

multiNo = pow((double)10, (digits-1));
gonzohunter
A: 

Simpler logic:

void print_digits(unsigned number) {
    unsigned next = number / 10;
    if ( next ) {
        print_digits( next );
    }

    printf( "-%d-", number % 10 );
    return;
}
Sinan Ünür
A: 

As a lazy programmer, I would print the digits this way:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  char Digits[ 129 ];
  printf( "Enter digits: " );
  gets( Digits );
  if( strlen( Digits ) < 1 )
  {
     printf( "\nNo digits!" );
     system( "PAUSE" );
     return 0;
  }
  printf( "Number of digits: %d\n\n", strlen( Digits ) );
  for( int Loop = 0; Loop < strlen( Digits ); Loop++ )
     printf( "Digit %d: %d\n", Loop, Digits[ Loop ] );
  system( "PAUSE" );
  return 0;
}