Created
September 25, 2011 14:46
-
-
Save ben0x539/1240664 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <math.h> | |
#define MSG "and the random number is: " | |
size_t num_length(long num) { | |
size_t result; | |
if (num == 0) { | |
return 1; | |
} else if (num < 0) { | |
result = 1; | |
num = -num; | |
} else { | |
result = 0; | |
} | |
result += floor(1 + log(num)/log(10)); | |
return result; | |
} | |
char* append(char* msg, long num) { | |
size_t old_length, new_length; | |
old_length = strlen(msg); | |
new_length = old_length + num_length(num) + 1; | |
msg = realloc(msg, new_length); | |
sprintf(msg + old_length, "%ld", num); | |
return msg; | |
} | |
int main(void) { | |
long num; | |
char* msg; | |
msg = malloc(sizeof(MSG)); | |
memcpy(msg, MSG, sizeof(MSG)); | |
srand(time(NULL)); | |
num = rand(); | |
msg = append(msg, num); | |
printf("%s\n", msg); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment