+ 1
Can I declare a variable by 2 data type?
When we have a calculation like "a/b", we have not known the value of a or/and b. So we have not known exactly the value of "a/b" is an integer or a float. I want to know exactly the value of "a/b". If a=7, b=2 => a/b = 3.5 For instance: { int a,b; int i; double i; i = a/b ; } Can I ?
9 Respuestas
+ 3
try 'union'
...
...
union X {
int a;
float b;
}x;
...
...
{
double i;
int p,q;
....//input p and q
i = p/q;
if (p%q==0)
x=(int)i;//x will behave like a int
else
x=(float)i;//x will behave like a float
...
...
}
try googling it for better understanding
+ 2
Just (double)a/b or a/(double)b.
+ 1
Sorry, I had not presented clearly
+ 1
Thanks. I think I have to learn more
0
It will give you an error.
0
you should cast a or b to be a double, because if not, a/b -> int/int -> int.
0
you can use type casting
0
no dear, it is wrong
0
{
int a=7, b=2;
float i;
i=a/b;
cout<<"i= "<<i<<endl;
return 0;
}