I'm new to C language, it is required for my degree to complete one course on C programming. Hope the title makes sense... I had a hard time trying to convey what I meant. I'll elaborate here.
The problem I am facing right now is double type data being able to slip through the program undetected when it should have been rejected. This happens when a number very very close to the boundaries I set is provided.
In this assignment, in order to get an HD, my code has to have identical output to the lecturer's. The solutions are able to detect any number larger than the boundaries, no matter how close.
Basically, the program will ask the user to provide a GPA which is from 0 to 4. I tried the following inputs: 4.01 rejected 4.001 rejected ... 4.000001 rejected But at 4.0000001, it is accepted. This should not happen at all. I am baffled.
Here's my code:
double GPA=-1; /*Flags are being initialised*/
int GPAflag=1;
while(GPAflag){
char str[50];
char *ptr;
int isnum=1,n=0,i,point=0;
printf("Enter GPA>");
fflush(stdin);
gets(str);
n = strlen(str);
if(n==0){ /*string length is 0? There was no input, thus invalid*/
printf("Invalid GPA. ");
isnum=0;
}else{
for(i=0;i<n;i++) /*Validates numerical inputs, if not numerical, prompts user with error*/
if(!(str[i]>='0' && str[i]<='9')){
if(str[i]!='.'){
printf("Invalid GPA. ");
isnum=0;
break;
}else{
point++;
}
}
}
if(isnum){ /*If the input is a number, it may still be invalid*/
GPA=strtod(str, &ptr); /*The string is converted to a double*/
if(GPA>=0&&GPA<=4&&point<=1) /*If GPA is between 0 and 4, and the above is also satisfied (point=1), then the flag is 0 and thus a valid input*/
GPAflag=0;
else
printf("Invalid GPA. "); /*If not, it is still invalid*/
}
}
I personally don't think this will be a problem but I would really like to know why it happens, and if possible, a way to fix it.
I can simply make a FOR loop: IF leading number is 4 and there's a '.' -> Reject But this seems like hard coding to me, I think it's rather a workaround than an actual solution. Or I can change the IF statement from "<=4" to "<4.0000000000000000000000...1". Which in my opinion should lose marks... (if I was the marker I will take marks off for that)
Also, I am totally aware that the function "gets" is primitive and causes many problems (overflow... etc.). I have tried using fgets but it's a pain to implement... replacing the '\n' with '\0' blah blah... we haven't even learnt gets, let alone fgets. Is there a better way to implement fgets? Maybe have a function to replace the '\n'? I've tried that and it refused to work.
Any help and tips are greatly appreciated!