Wednesday, 25 August 2010

Positional notation of numbers in c

Positional notation of numbers

#include <>
#include <>

#define PACKAGE "digits"

int number_of_digits(int x);
void print_help(void);

int main(int argc, char *argv[]) {
int n; /* input; the number to convert */
short base; /* input; base to which we will convert n */
short rhdigit; /* right-hand digit of n-prime */
int power; /* loop */

if(argc != 3) {
print_help();
return 1;
} else {
sscanf(argv[1], "%d", &n);
if(n < 1) {
fprintf(stderr, "%s: Error: Number must be greater than 0.\n", PACKAGE);
return 1;
}

sscanf(argv[2], "%hi", &base);
if(base <> 10) {
fprintf(stderr, "%s: Error: Base is not in required range.", PACKAGE);
return 1 ;
}
} /* else */

printf("The number %d, is %d wide, ", n, number_of_digits(n));
printf("and contains the numbers: ");

/*
// Generate digits of converted number, right to left.
*/
for(power = 0; n != 0; power++) {
rhdigit = n % base; /* Isolate right-hand digit of n. */
n /= base; /* then eliminate right-hand digit. */

printf("%hi ", rhdigit);
}

printf("\n");
return 0;
}

int number_of_digits(int x) {
return x ? (int)(log10((double)(abs(x))))+1 : 1;
}

void print_help(void) {
fprintf(stdout, "Usage : %s [NUMBER] [BASE]\n", PACKAGE);
fprintf(stdout, "Example: %s 4591 10\n", PACKAGE);
}

No comments:

Post a Comment