|
|
|
The int value 4 is represented as:
00000000 00000000 00000000 00000100 (this is the encoding of 4 in int)
|
|
|
|
|
|
|
public class JavaFunc1
{
public static int f(float x)
{
return (int) (x*x);
}
public static void main(String[] args)
{
int a;
float b;
a = 4;
b = f(a); // int a is converted to float before calling f
// int return value is converted to float
// before assigning to b
System.out.println("a = " + a + ", b = " + b);
}
}
|
How to run the program:
|
public class JavaFunc2
{
public static float f(int x)
{
return (x*x);
}
public static void main(String[] args)
{
float a;
int b;
a = 4;
b = f(a); // cannot convert float a to int parameter safely !!!!
System.out.println("a = " + a + ", b = " + b);
}
}
|
Result:
cheung@aruba> javac JavaFunc2.java
JavaFunc2.java:17: error: method f in class JavaFunc2 cannot be applied to given types;
b = f(a);
^
required: int
found: float
reason: actual argument float cannot be converted to int by
method invocation conversion
1 error
|
How to run the program:
|
|
#include <stdio.h>
int f(float x)
{
return (int) (x*x);
}
void main(int argc, char * argv[])
{
int a;
float b;
a = 4;
b = f(a); // C will convert int a to float
// C will also convert the int return value to float
printf("a = %d, b = %f\n", a, b);
}
|
How to run the program:
|
#include <stdio.h>
float f(int x)
{
return (x*x);
}
void main(int argc, char *argv[])
{
float a;
int b;
a = 4;
b = f(a); // C compiler will convert float a to int
// C compiler will also convert float return value to int
printf("a = %f, b = %d\n", a, b);
}
|
How to run the program:
|