+ 1

Can't initialize with this fraction

I can't get variable "dis" to initialize with an expression that includes a fraction. The output for the "dis" variable is "0" other than when I replace the expression with a constant. Any insight would be greatly appreciated. Code: #include <iostream> using namespace std; double getDis(int var) { double dis; dis = (50/100)*var; return dis; } int main() { int ages[5]; for (int i = 0; i < 5; ++i) { cin >> ages[i]; } //your code goes here double min {ages[0]}; for (int i = 1; i < 5; i++) { if (ages[i] < min) min = ages[i]; } //cout << "min = " << min << endl; double dis{getDis(min)}; //dis = (50/100)*min; double cost {50-dis}; cout << cost; return 0; }

27th Jul 2021, 12:09 PM
Arran
Arran - avatar
6 ответов
+ 7
(50/100) returns 0 since neither operands are double. Try (50.0/100), and yeah, you should be returning double from the function too, not int.
27th Jul 2021, 12:25 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Int type will remove all the values after decimal point. Maybe use float or double.
27th Jul 2021, 12:15 PM
Abhay
Abhay - avatar
+ 2
Arran change the type of function as well otherwise it will return an int .
27th Jul 2021, 12:21 PM
Abhay
Abhay - avatar
+ 2
Thank you both for taking the time to solve my issue
27th Jul 2021, 12:28 PM
Arran
Arran - avatar
+ 1
Thank you for the advice. It returns 0 whichever type I use. I just noticed my function had int and replaced with double, and it again returned 0.
27th Jul 2021, 12:18 PM
Arran
Arran - avatar
+ 1
Hatsy Rei, that was exactly the issue, thank you!
27th Jul 2021, 12:27 PM
Arran
Arran - avatar