All pastes #907682 Raw Edit

Something

public text v1 · immutable
·published 2008-02-17 20:49 UTC
rendered paste body
It handles '123', '456', and '789' properly, but when given those same numbers in a different order, '789
, '456', '123', it spits back that 789 is the greatest, 123 is next, and 456 is last.









/*
 *  Exercise1.3.c
 *  
 *
 *
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define JARSIZE 3

static int getdigit(void);
static int compare_val(const void *a, const void *b);

int main(void){
	printf("It begins!\n");
	// use getdigit to recieve numbers from the user
	// put them into an array, sort the array, and return it
	
	int it = 0;
	int cookiejar[JARSIZE] = { 0 };
	
	while (it < JARSIZE){
		cookiejar[it++] = getdigit();
	}
	for(it=0;it<JARSIZE;it++){
		printf("This element: %d\n", cookiejar[it]);
	}
	printf("Begin sorting\n");
	qsort(cookiejar, JARSIZE, sizeof(int), compare_val);
	// debug
	for(it=0;it<JARSIZE;it++){
		printf("This element: %d\n", cookiejar[it]);
	}
	
	return 0;
}

// comparison function taken from gnu.org
// libc manual
int compare_val(const void *a, const void *b) {
	const double *da = (const double *) a;
	const double *db = (const double *) b;
	
	return (*da > *db) - (*da < *db);
}

int getdigit(void){
	/*
		The goal of this functio is to take digits entered by the user
		and return them as one single digit.
		For example, is the user entered 1, 2 and 4, it returns
		124.
	*/
	char * pEnd;
	int i, c, n, factor,  digit[9] = { 0 };
	
	i = 0;
	
	printf("Enter Digits.\n");
	
	while((c = getchar()) != '\n' && i != 9){
		// Until newline or 9 digits are captured, take digits and put them in
		// c
		// c is now the int cast of the unsigned char that getchar returned
		
		if( c >= '0' && c <= '9') {
			// if C is a digit between 0 and 9
			digit[i++] = c - '0';
			printf("Your number is: %d\n", digit[(i-1)]);
			// subtracting 0 from c turns the result into ascii?
		} else {
			printf("INVALID INPUT - digits only\n");
			exit(0);
			// user did not enter a digit between 1 and 9.
		}
	
	}

	n = i;
	c = 0;
	factor = 1;
	for(i=n-1; n != 0; n--){
		c += (digit[i--] * (int)factor);
		factor = factor * 10;
	}
	return c;
}