0

I'm new to coding and this is my "first" c program, can someone please explain to me the reason why it keeps bypassing the character scan at the loop ending? It doesn't loop around and there is no character request at the end of the execution.

#include<stdio.h>
#include<math.h>
int main(){
    int a,b,c,quad;
    float x,x1,x2;
    char ch='y';
    printf("Insert consecutive factors a,b,c:\n");
    while(ch=='y'){
        scanf("%d%d%d",&a,&b,&c);
        quad=((b*b)-(4*a*c));
        printf("Δ: %d\n",quad);
        if(quad>0){
            x1=((((-1*b)+(sqrt(quad)))/(2*a)));
            x2=((((-1*b)-(sqrt(quad)))/(2*a)));
            printf("The results are x1=%3f and x2=%3f\n",x1,x2);
        }else if(quad==0){
            x=(-1*b)/(2*a);
            printf("The result is x=%3f\n",x);
        }else{
            printf("The equation has no solution\n");
        }
    printf("Do you wish to continue?[y/n]:");
    scanf("%c",&ch); 

//correct way is scanf(" %c",ch);

    }
return 0;
}

I tried changing the while{} loop to a do{}while cause i thought it was a problem with the condition evaluation timing but didn't work.

  • 1
    Use scanf(" %c",&ch); Pay attention to the leading space in the format string. It allows to skip white space characters. – Vlad from Moscow Oct 30 '22 at 19:27
  • Change `scanf("%c",&ch);` to `scanf(" %c",&ch);`. That way it will skip past the previous newline character and wait for you to enter the y/n response you want. – Tom Karzes Oct 30 '22 at 19:32

0 Answers0