public class project3 {
public static void main(String[] args) {
int earnedRuns = 52;
int inningsPitched = 182;
double ERA = (earnedRuns * 9) / inningsPitched;
String FirstName = "Anibal";
String LastName = "Sanchez";
System.out.println("Pitcher's first name: " + FirstName);
System.out.println("Pitcher's last name: " + LastName);
System.out.println("Number of earned runs: " + earnedRuns);
System.out.println("Number of innings pitched: " + inningsPitched);
System.out.println(FirstName + " " + LastName + " has an ERA of " + ERA);
}
}
The ERA comes out as 2.0 not 2.57... ect
I cannot figure out why
BackSlash
22.3k25 gold badges103 silver badges143 bronze badges
1 Answer 1
Baically you're:
- multiplying an integer by an integer -> integer (Result: 486)
- dividing an integer by an integer -> integer (Result: 2)
- Assign the result to an double variable -> double (Result: 2.0D)
So you first need to cast ("convert") those integers to floats or doubles.
double ERA = ((double)earnedRuns * 9) / inningsPitched;
or simpler:
double ERA = (earnedRuns * 9.0) / inningsPitched;
It's enough to cast just one integer because in java: integer * double -> double
EDIT:
The 9.0 D or 9.0 d just tells java that explicitly that 9.0 is meant to be a double. The same also works for 9.0 f or 9.0 F. This means that 9.0 is a float.
answered Feb 16, 2014 at 21:16
maxammann
1,0483 gold badges11 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
user3316886
thank you. it was telling me to change the integers to doubles as well but that was not the assignment.
maxammann
np and don't forget if the answer was helpful, accept it as answer :D
lang-java