0

Can anyone explain me why this code is giving 0 as a output

#include <iostream> using namespace std; int main() { float purchaseAmount1, purchaseAmount2, purchaseAmount3; float discount1, discount2, discount3; // your code goes here cin >> purchaseAmount1; cin >> purchaseAmount2; cin >> purchaseAmount3; discount1 = (15 / 100) * purchaseAmount1; discount2 = (15 / 100) * purchaseAmount2; discount3 = (15 / 100) * purchaseAmount3; cout << discount1 << endl; cout << discount2 << endl; cout << discount3 << endl; return 0; }

4th Nov 2022, 2:24 PM
Shreyansh
Shreyansh - avatar
2 ответов
+ 2
15 / 100 Here you are doing integer division, whatever fractal there was in result, will be truncated, and you only get the whole number. 15 / 100 0.15, but the .15 fractal will be truncated, and you only will get the 0 (zero) Use floating point literal for generating the percentage discount1 = ( 15.0 / 100 ) * purchaseAmount1; // notice 15.0 is a floating point value Or, if the discount percentage is constant, you can directly calculate discount1 = 0.15 * purchaseAmount1; // using floating point literal const float percentage = 0.15f; discount1 = percentage * purchaseAmount1; // using constant <percentage>
4th Nov 2022, 2:51 PM
Ipang
+ 1
Thanks Ipang I got the answer
4th Nov 2022, 3:01 PM
Shreyansh
Shreyansh - avatar