Jump to content

Here's something to exercise your number base conversion skills

- - - - -

  • Please log in to reply
2 replies to this topic

#1
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
This program displays decimal numbers at random and prompts for the number in hex, telling you if you got it correct. It can easily be modified to convert hex to decimal, hex to octal, etc.


#include <stdio.h>

#include <stdlib.h>

#include <time.h>


int random( int );


int main( int argc, char **argv ){

	printf( "Enter the given number in hexadecimal.\n(Values must be in lowercase)\n" );

	for(;;){  // Loops until the user enters 0 or an invalid value or sends an interrupt

		unsigned int dec = (unsigned int) random( 256 );

		unsigned int hex;

		printf( "%d: ", dec );

		scanf( "%x", &hex ); // Input hexadecimal value

		if( !hex ){

			printf( "Bye\n" );

			break;

		}

		else{

			if( dec == hex )

				printf( "\e[32mCorrect\e[0m\n" ); // Prints in green.

			else

				printf( "\e[31mIncorrect\e[0m\nThe correct answer is %x\n", dec );

				// Prints in red.

		}

	}

	return 0;

}


// I wrote my own random number generator function because memorizing

// srand is tedious and unnecessary.

int random( int mod ){

	int t = (int) time(NULL);

	int r = rand();

	return abs( (t*r)%mod );

}


Programming is a journey, not a destination.

#2
stevie754

stevie754

    Programmer

  • Members
  • PipPipPipPip
  • 110 posts
Thanks I have been learning binary and hexidecimal in school and this will be a good way to revise over the summer until its needed again.

#3
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
Neat script!

Two things though,
1) You include "unsigned int ..." inside the for loop, this is alright because it is in the stack and may be reclaimed, instead you should help the compiler and declare them outside.
2) Your !hex will never do anything and an invalid character will result in an infinite loop, you should always check the result of scanf, and never ignore it:
        if( scanf( "%x", &hex ) == 0) {; // If scanf has parsed 0 specified tokens from stdin
            printf( "Bye\n" );
            break;
        }

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users