Problems with arithmetic operators in C++

Asked

Viewed 37 times

0

I’m trying to get the program to calculate the discount value of a certain value entered by the user;

#include <iostream>
#include <stdio.h>
#include <locale.h>

using namespace std;

int main()
{

    float number1, number2, desconto;

    cout << "Digite o valor de compra do seu produto R$ ";
    cin >> number1;

    desconto = number1 * (30 / 100);
    number2 = number1 - desconto;

    cout << "O produto custa R$ " << number2 << " reais com 10% de desconto.";

    system("pause");
    return 0;
}
  • I’m seeing a problem, but it would help if you described what’s happening differently than expected, and what your difficulty is.

  • for example: if I enter with the value of 120 the program does not return me the correct value that would be the discount of 30%, returns me the same 120

  • So the values 30 and 100 are integers, and the result of dividing whole numbers is an integer, that is, it will be 0. If you want the result to be 0.3, should do 30.0 / 100.0.

  • Thanks bro, it was just that, it worked out great!!!

1 answer

0

Respondent based on user comment user140828.

The problem is that in the division of 30 by 100 you are using integers and the value ends up being truncated to zero. This is because integer type variables cannot store decimal numbers.

To get the correct value just change the type of the number 30 to float (floating-point):

desconto = number1 * (30.0 / 100);

Thus the result of the operation 30.0 / 100 becomes 0.3 and it just stops being 0.

Browser other questions tagged

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