saving . . . saved Assignments has been deleted. Assignments has been hidden .
Assignments
Title
Question
#include <iostream>
using namespace std;

int main() {
   int a, b, c, d;
   cout<<"Enter a and b: ";
   cin>>a>>b;
   cout<<"Enter c and d: ";
   cin>>c>>d;
   float ans = (a/b)+(c/d);
   cout<<"Answer(without typecast) = "<<ans<<"\n";
   
   ans = ((float)a/b)+((float)c/d);
   cout<<"Answer(with typecast) = "<<ans<<"\n";
   return 0;
}

Why the output is in 'int' type but not 'float' type?
But the same program in C came with output of 'float' type.

C-and-Cpp Increment-And-Decrement-Operators 11-12 min 20-30 sec 20-06-21, 10:34 p.m. Sujan_A_T

Answers:

Dear <span style="background-color: rgb(245, 245, 245);">Sujan_A_T,</span>
<span style="background-color: rgb(245, 245, 245);">     Assuming all variables are of type integer, statement </span><span style="background-color: rgb(250, 250, 250);">float ans = (a/b)+(c/d); will be evaluated using integer division, as there is no typecast applied. </span><span style="background-color: rgb(245, 245, 245);"> For the statement, </span><span style="background-color: rgb(250, 250, 250);">ans = ((float)a/b)+((float)c/d); the value of variable 'ans' will contain the floating value as both divisions are typecasted to float value and added subsequently. </span>


For the c version, you can have a look here:
#include <stdio.h>

int main() {
   int a, b, c, d;
   float ans;
   printf("Enter a and b: ");
   scanf("%d %d", &a, &b);
   printf("Enter c and d: ");
   scanf("%d %d", &c, &d);
   ans = (a/b)+(c/d);
   printf("Answer(without typecast) = %f\n",ans);

   ans = ((float)a/b)+((float)c/d);
   printf("Answer(with typecast) = %f\n", ans);
   return 0;
}

The sample input and output is given below:
Enter a and b: 2 3
Enter c and d: 4 5
Answer(without typecast) = 0.000000
Answer(with typecast) = 1.466667

You can see, without typecasting, the integer division is performed and then typecasted to float. So, the decimal values are truncate din the integer  division

Try experimenting to see for yourself. Hope this answers your question

Spoken Tutorial Team

<span style="background-color: rgb(250, 250, 250);">
</span>
13-07-21, 4:36 p.m. nags
Thank you so much.
I'm really great ful to you.
Now I got a confidence to learn even though I'm not IIT'an.
Thank you once again.

13-07-21, 4:56 p.m. Sujan_A_T

Login to add comment


Log-in to answer to this question.