Ad

The Code Below Is Supposed To Take Initial Inputs And Is Supposed To Keep On Asking For Inputs Until The Both Inputs Are From 0 To 2000

- 1 answer

the code below is supposed to take initial inputs and is supposed to keep on asking for inputs until the both inputs are from 0 to 2000 but only asks if both are less than 0 or greater than 2000

int main(){

    float x;
    int y;
    scanf("%f",&x);
    scanf("%d",&y);
while(!(x>0 && x<=2000) && !(y>0 && y<=2000)){
    printf("invalid balance or initial amount\n");
    printf("enter initial balance\n");
    scanf("%f",&x);
    printf("enter withdrawal amount\n");
    scanf("%d",&y);
    continue;
     }
return 0;

}

Ad

Answer

The simple answer: change the middle && to ||:

while (!(x>0 && x<=2000) || !(y>0 && y<=2000)) {

Or, you can use an equivalent:

while (! ((x>0 && x<=2000) && (y>0 && y<=2000))) {

But, I'd clean this up a bit because the initialscanf calls [before the loop] don't prompt the user. So, I'd reverse the logic a bit:

#include <stdio.h>

int
main(void)
{
    float x;
    int y;

    while (1) {
        printf("enter initial balance\n");
        scanf("%f", &x);

        printf("enter withdrawal amount\n");
        scanf("%d", &y);

        if (((x > 0) && (x <= 2000)) && ((y > 0) && (y <= 2000)))
            break;

        printf("invalid balance or initial amount\n");
    }

    printf("x=%g y=%d\n",x,y);

    return 0;
}
Ad
source: stackoverflow.com
Ad