There are two classes of input for factorials:
#include <stdio.h> int main(void) { printf("%f\n", 90.1); printf("%.15f\n", 90.1); return 0; } |
90.100000 90.099999999999994 |
To be sure that truncation is not masking solutions, an extra loop could be added to make sure that rootn is large enough. In other words:
int rootn; rootn = sqrt(n); // this assignment truncates: does rootn * rootn = n, I wonder while (rootn * rootn < n) { // extra loop to overcome possible truncation error rootn++; } |
One possible fix is:
int findWord(char *word, char *wordList[], int nwords) { int found = -1; // this is returned if no match int i; for (i = 0; i < nwords; i++) { if (strcmp(wordList[i],word) == 0) { found = i; } } return found; } |
// Use a flag to stop the search int findWord(char *word, char *wordList[], int nwords) { int found = -1; int i = 0; while (i < nwords && found < 0) { if (strcmp(wordList[i],word) == 0) { found = i; // found the word } else { i++; // not a match, try next } } return found; } |
// Possibly avoid calling strcmp() by checking first letter matches int findWord(char *word, char *wordList[], int nwords) { int found = -1; int i = 0; while (i < nwords && found < 0) { if ((*wordList[i] == *word) && (strcmp(wordList[i],word) == 0)) { found = i; // found the word } else { i++; // not a match, try next word } } return found; } |
char *strncat(char *dest, char *source, int n) { int i; char *d = dest; char *s = source; while (*d != '\0') { d++; } i = 0; while (*s != '\0' && i < n) { *d = *s; d++; s++; i++; } *d = '\0'; return dest; } |
char dest[8] | char src[8] | n | Expected | Note |
"" | "" | 0 | "" | n == length(src) |
"" | "abc" | 3 | "abc" | n == length(src) |
"" | "abcd" | 3 | "abc" | n < length(src) |
"abc" | "" | 0 | "abc" | n == 0 |
"abc" | "defg" | 0 | "abc" | n == 0 |
"abc" | "defg" | 3 | "abcdef" | normal case |
"abcd" | "efgh" | 3 | "abcdefg" | exactly fills dest |
"abc" | "" | 2 | "abc" | error, n > length(src) |
"abcd" | "efgh" | 4 | undefined | error, overfills dest |