Data Type Mismatch Error in C++ Code: Rectification Needed

light2

Recruit
I need help with a data type-related problem in my C++ code. I've tried a few different approaches and have read various , but I haven't had any luck. This is a sample of the code that causes issues:

C++:
#include <iostream>

int main() {
    float totalAmount;
    int discountPercentage;

    std::cout << "Enter total amount: ";
    std::cin >> totalAmount;

    std::cout << "Enter discount percentage: ";
    std::cin >> discountPercentage;

    float discountedAmount = totalAmount - (totalAmount * discountPercentage / 100);

Despite seemingly correct logic, the code is producing unexpected results. The discount calculation appears to be incorrect. What data type-related error might be causing this issue, and how can I rectify it to ensure accurate discount calculations?
   
    std::cout << "Discounted Amount: " << discountedAmount << std::endl;

    return 0;
}
 
Last edited by a moderator:
I need help with a data type-related problem in my C++ code. I've tried a few different approaches and have read various articles, but I haven't had any luck. This is a sample of the code that causes issues:

C++:
#include <iostream>

int main() {
    float totalAmount;
    int discountPercentage;

    std::cout << "Enter total amount: ";
    std::cin >> totalAmount;

    std::cout << "Enter discount percentage: ";
    std::cin >> discountPercentage;

    float discountedAmount = totalAmount - (totalAmount * discountPercentage / 100);

Despite seemingly correct logic, the code is producing unexpected results. The discount calculation appears to be incorrect. What data type-related error might be causing this issue, and how can I rectify it to ensure accurate discount calculations?
   
    std::cout << "Discounted Amount: " << discountedAmount << std::endl;

    return 0;
}
In c/c++ the result of an arithmetic operation between 2 same type variables/literals will result in a variable of same type (this does not hold true for operator overloading, but let's not think about that now). discountPercentage is int, 100 is int, the result of the division will also be an int. Assuming discountPercentage is < 100, the result will be 0.

To fix, you need type casting, either implicit (discountPercentage/ 100.0) or explicit (using static_cast<float>, recommended, or c style cast, (float), not recommended).
 
Last edited:
Back
Top