Home > Software engineering >  i want to do a sum between 2 numbers, if the number is above 20 the program will add 8 and if it is
i want to do a sum between 2 numbers, if the number is above 20 the program will add 8 and if it is

Time:12-18

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

int main(void)
{
    int num1, num2, result, result2, result3;

    printf("Primeiro numero: \n", num1);
    scanf("%d", &num1);
    printf("Segundo numero: \n", num2);
    scanf("%d", &num2);

    result = num1   num2;

    if (result > 20) {

        result2 = result   8;

        printf("Resultado: %d \n", result2);
        scanf("%d", &result2);
    }

    else {
        (result < 20);

        result3 = result - 5;

        printf("Resultado: %d \n", result3);
        scanf("%d", &result3);
    }
}

CodePudding user response:

Please remove the scanf from your if/else statements. your else statement has (result < 20); which does nothing. So you have remove it too.

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

int main ()

{
    
    int num1, num2, result;
    printf("Primeiro numero: ");
    scanf("%d", &num1);
    printf("Segundo numero: \n");
    scanf("%d" , &num2);
    
    result = num1   num2;
    
    
    if (result > 20) {    
        printf("Resultado: %d \n", result   8);
    }
    else {
        printf("Resultado: %d \n", result - 5);
    }
    
    return 0;

}

CodePudding user response:

You have a few errors in your code:

printf("Primeiro numero: \n", num1);

num1 is not initialized there. You are reading it in the next line of code with a scanf. Just print a message telling the user to enter a number, then read it, then read the number.

(result < 20);

That check should go together with the else. So you first check result > 20, then, if that is not true, you go on and check result < 20. Notice you are not checking result == 20.

scanf("%d", &result2);
scanf("%d", &result3);

Those 2 lines are not needed. You just want to print some results, not read them from the user.

Also:

  • Prefer to declare variables closer to the place you are first going to use them.
  • Try and initialize variables when you declare them.
  • You don't really need to declare result2 and result3.

[Demo]

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

int main (void)
{
    int num1 = 0;
    int num2 = 0;
    
    printf("Primeiro numero: ");
    scanf("%d", &num1);
    printf("%d\n", num1);
    printf("Segundo numero: ");
    scanf("%d", &num2);
    printf("%d\n", num2);
    
    int result = num1   num2;

    if (result > 20) {
        printf("Resultado: %d\n", result   8);
    }
    else if (result < 20) {
        printf("Resultado: %d\n", result - 5);
    }
}
  • Related