Miscalculation with While

Asked

Viewed 42 times

0

In this exercise it is to type two numbers and print on the screen themselves, and the integers between them. However, if I type for example 10 and 20, the last number that appears is 19 instead of 20; and if I type 20 and 10, the last number appears 11.

My mistake is not in ifFor what I have tested, I may be wrong.

NOTE: I need to use while.

#include <stdio.h>
#include <stdlib.h>

int n1, n2;

main()
{
    printf("Para saber os inteiros entre dois numeros siga os passos abaixo: \n");
    printf("Digite o primeiro numero: ");
    scanf("%d", &n1);
    printf("Digite o segundo numero: ");
    scanf("%d", &n2);
    system("cls");
    if((n1 == n2)||(n2 == n1)){
            printf("NUMEROS IGUAIS!\n");
    }
    while((n1 < n2)||(n1 > n2))
    {
         if(n1 < n2){
            printf("%d\n", n1);
            n1 = n1 + 1;
        }else if(n1 > n2){
            printf("%d\n", n1);
            n1 = n1 - 1;
        }
    }
    return 0;
}


  • Need to better define the problem if it is to print the numbers between them is to print from 11 to 19.

  • I edited the question, I think it’s clearer now.

2 answers

1


The main problem is that it is stopping when it is larger or smaller, but you want to include the value within the limit, so you have to accept when the value is equal to the limit too so you would need to use r <= and >= in the while.

This code is too complex and inefficient to do several operations without any need (3 branches in each step against 1 of mine). So I think it best to do so:

#include <stdio.h>

int main() {
    int n1, n2;
    printf("Para saber os inteiros entre dois numeros siga os passos abaixo: \n");
    printf("Digite o primeiro numero: ");
    scanf("%d", &n1);
    printf("Digite o segundo numero: ");
    scanf("%d", &n2);
    if (n1 == n2) printf("NUMEROS IGUAIS!\n");
    else if (n1 < n2) while (n1 <= n2) printf("%d\n", n1++);
    else while (n1 >= n2) printf("%d\n", n1--);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • It is that in this exercise would need to use while (the teacher asked).. I tried to put how you spoke <= and >= inside the while, but now the code has been running endlessly.

0

Use the operator <= in your condition, like:

do {
     if(n1 <= n2){
       printf("%d\n", n1);
       n1 = n1 + 1;
     } else {
       printf("%d\n", n1);
       n1 = n1 - 1;
     }
 } while((n1 <= n2)||(n1 => n2));    
  • Worse than the result is still the same as I said up there.. i’m guessing there’s something wrong in the condition that I put in while.. but I’m not managing to find the problem.

  • Try using Do While, I edited the code above, I made it here with javascript and ran right here.

Browser other questions tagged

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