Do-while with char in C

Asked

Viewed 58 times

0

EX. Create a program that reads sales values (old and new) of a product. The program must calculate the percentage increase of the product. The program ends only when the user informs the letter "N" for the question "Calculate the percentage of increase of the next product?". Case the user answer "S" to this question, the sale values new and old should be read for a new product.

I stopped at the part where I need to make the program continue running from the user’s response. Can someone please explain to me what I did wrong or failed to do? My code so far:

int main() {

  float v1,v2;
  char produto[30];
  int aumento;
  char resposta;

do {
  printf("Digite o nome do produto:\n");
  fgets(produto,30,stdin);
  system("cls");

  printf("Digite o valor antigo do produto %s",produto);
  scanf("%f", &v1);
  system("cls");

  printf("Digite o novo valor do produto %s",produto);
  scanf("%f", &v2);
  system("cls");

  //formula aumento em %
  aumento = (v2 - v1) / v1 * 100;
  printf("O aumento foi de %d por cento.\n",aumento);

  printf("Calcular o percentual do proximo produto? (S/N)\n");
  scanf("%c", &resposta);
    if(resposta == 'N' || resposta == 'N')
    exit(0);
  }

while(resposta != 'n' || resposta != 'N');

    return 0;
}

1 answer

1

Your error is in the {} while conditional ();

Analyze the truth table:

answer != 'n' answer != 'N' answer != 'n' || answer != 'N' Commentary
0 0 0 This situation will never occur!
0 1 1
1 0 1
1 1 1
0 0 0 This situation will never occur!
0 1 1
1 0 1
1 1 1

Basically, your conditional will always return the true value, not obeying the user when he wants to terminate the application.

This is because 'n' = 'N', so when the user type 'n', the second condition will be true, and vice versa.

In short:

To solve, change the OR (||) for AND (&&) on your while’s probation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.