loops - GPA Calculator in C -
i'm trying code calculate class's average gpa. problem i'm having seem have made mistake in do...while
code, because, when run it, loops asking me input gpa, rather asking if want calculate average or not.
#include<stdio.h> int main() { float fagpa[30], fsum = 0, favg = 0; int x, y; char cresp = '\0'; printf("\t\tgpa calculator\n"); printf("\nenter 30 gpas calculator.\n"); do{ printf("\nenter gpa: "); scanf("%f", &fagpa[x]); x++; printf("\ncalculate gpa average (y/n)?\n"); scanf("%c", &cresp); } while(x < 30 && cresp != 'y' || x < 30 && cresp != 'y'); for(y = 0; y < (x + 1); y++) fsum += fagpa[y]; favg = (fsum / (y - 1)); printf("\nthe class gpa is:%.2f", favg); return 0; }
there 2 issues here. first, need discard new lines on scanf. see here details.
second || operator going cause whole statement evaluate true no matter if user has entered y or y. try switching && operator , closing 2 checks in own parenthesis.
see sample below - should @ least further, though i'm still not getting right answer math.
float fagpa[30], fsum = 0, favg = 0; int x = 0, y = 0; char cresp = '\0'; printf("\t\tgpa calculator\n"); printf("\nenter 30 gpas calculator.\n"); do{ printf("\nenter gpa: "); scanf("%f", &fagpa[x]); x++; printf("\ncalculate gpa average (y/n)?\n"); scanf("\n%c", &cresp); } while (x < 30 && (cresp != 'y' && cresp != 'y')); (y = 0; y < (x + 1); y++) fsum += fagpa[y]; favg = (fsum / (y - 1)); printf("\nthe class gpa is:%.2f", favg); return 0;
Comments
Post a Comment