#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 );
}
Here's something to exercise your number base conversion skills
Started by DarkLordofthePenguins, Feb 14 2011 03:09 AM
2 replies to this topic
#1
Posted 14 February 2011 - 03:09 AM
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.
Programming is a journey, not a destination.
|
|
|
#2
Posted 24 March 2011 - 01:06 AM
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
Posted 24 March 2011 - 08:41 PM
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:
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.
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


Sign In
Create Account


Back to top










