+ 1

Area of triangle is ZERO! (This is a question from challenge). The output is different in both cases below. What's the reason?TY

//CASE - 1 #include <iostream> using namespace std; int main() { float area, base = 5, height = 10; area = (1/2)*base*height; cout<< area; return 0; } // Output = 0 // CASE - 2 #include <iostream> using namespace std; int main() { float area, base = 5, height = 10; area = (0.5)*base*height; cout<< area; return 0; } // Output = 25

7th Jun 2020, 3:48 AM
Chocolate
Chocolate - avatar
2 Réponses
+ 6
In the first case, (1/2) is treated as integer division, with 0.5 getting truncated to 0, which in turn turns the entire product into zero. Writing 1 as 1.0 would easily solve that problem.
7th Jun 2020, 3:51 AM
Harsh
Harsh - avatar
+ 3
Stellar Fox , ~ swim ~ I was thinking like this ↓ (1/2) = 0.5 it's a double so it will be used in operation without removing "5". But I get it now. An integral fraction will not be treated the same as a float type fractional value. (And being in the middle of a calculation won't save those integer numbers from being attacked by double! 😈) Thank you two!
7th Jun 2020, 9:18 AM
Chocolate
Chocolate - avatar