• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Beginner Java question

B.def

Member
I am trying to convert an int value to double.
This is what I'm working with. I am not aloud to declare the variables with a double, only int.

Code:
double a=0,b=1,c=2,d=3;
double average= (a+b+c+d)/4;
System.out.println("The average of " + a + " " + b + " " + c + " and "+d+" is "+average);
Result
Code:
run:
The average of 0.0 1.0 2.0 and 3.0 is 1
BUILD SUCCESSFUL (total time: 0 seconds)
I need the average to be more than integer.
 
double a=0,b=1,c=2,d=3;
double average= (a+b+c+d)/4.0;
System.out.println("The average of " + a + " " + b + " " + c + " and "+d+" is "+average);

See correction.

The reason you're getting the answer you are is due to the way certain values are stored.

Even though you've declared them as doubles, you assigned them integer values.

int / int= int (even if the result has decimals, they are truncated)
int / double = double (result is 'promoted')
 
Last edited:
I'm sorry I typed it in wrong. the values defined up top are suppose to be int values as shown below
Code:
int a=0,b=1,c=2,d=3;
double average=(double)(a+b+c+d)/4;
System.out.println("The average of " + a + " " + b + " " + c + " and "+d+" is "+average);
I tested some other things out and realized I had to plug in double into the average equation to get the double values.

Thanks for the quick response though.
 
just bare in mind that the double cast has bound to the top result:
double average=((double)(a+b+c+d))/4

Pushing either top of bottom of the calc to be a double will make the entire calculation happen as a double.
 
Back
Top