Stephen Cadiz Stephen Cadiz - 26 days ago 6
C Question

C - Print a char returned by a function

UPDATE:
The final if statement

if(lettergrade <= 'A' && lettergrade >= 'F')
was incorrect as the ascii value for F (70) is greater than A (65).

I'm trying to print a character returned by a function in C.

My function, assignletter, is given a float, and returns a character.

When I run the program as is:

skirchbaum:~/workspace/HMWK/HMWK4 $ ./assignletter
Enter pointsgrade
100
Pointsgrade: 100.00 Lettergrade:


Nothing gets printed for lettergrade (I have tried multiple cases - 100.1, 1, etc)

What am I doing wrong?

CODE:

/* Input: a grade as points
Functionality: converts point grade into letter grade
Output: a char representing the letter grade, or -1 if error

LETTER GRADE BREAKDOWN:
A = 100 - 91
B = 90 - 81
C = 80 - 71
D = 70 - 61
F = 60 and below
*/


#include <stdio.h>
#include <stdlib.h>
#define DEBUG 1

char assignletter(float pointsgrade);

char lettergrade;
float pointsgrade;

int main(){
//Input a pointsgrade for debugging
#ifdef DEBUG
printf("Enter pointsgrade\n");
scanf("%f", &pointsgrade);
lettergrade = assignletter(pointsgrade);
printf("Pointsgrade: %.2f Lettergrade: %c\n", pointsgrade, lettergrade);
#endif
}

char assignletter(float pointsgrade){

char lettergrade;

//Grade A
if(pointsgrade <= 100 && pointsgrade >= 91){
lettergrade = 'A';
}

//Grade B
if(pointsgrade <= 90 && pointsgrade >= 81){
lettergrade = 'B';
}

//Grade C
if(pointsgrade <= 80 && pointsgrade >= 71){
lettergrade = 'C';
}

//Grade D
if(pointsgrade <= 70 && pointsgrade >= 61){
lettergrade = 'D';
}

//Grade F
if(pointsgrade <= 60){
lettergrade = 'F';
}

//Return letter grade or -1 if error
if(lettergrade <= 'A' && lettergrade >= 'F'){
return lettergrade;
}
else{
return -1;
}
}

Answer

the condition is not well formed, the 'F' is 70 in ASCII and the 'A' is 65 so

if (lettergrade <= 'A' && lettergrade >= 'F') {
    return lettergrade;
}

won't evaluate to true as lettergrade ('A') is less than 70 ('F') and not bigger than it

you'd rather do it this way

if (lettergrade >= 'A' && lettergrade <= 'F') {
    return lettergrade;
}

by flipping the bigger than and less than signs