Hello,
I am having an issue with casting. See code below:
class GDPPerCapita { public static void main(String[] args) { // Declare variables int gdp = 175000; int population = 4000; double gdpPerCapita = (double)gdp/population; // = 43.75 int gdpPerCapitaDollars = (int)gdpPerCapita; // = 43 int gdpPerCapitaCents = gdpPerCapita - gdpPerCapitaDollars; // Should equal 75 as an int, but isn't System.out.println("GDP: $" + gdp); System.out.println("Population: " + population); System.out.println("GDP Per Capita: $" + gdpPerCapita); System.out.println("GDP Per Capita: " + gdpPerCapitaCents + "Dollars and " + gdpPerCapitaCents + " Cents"); } }
Desired output should look as follows:
GDP: $175000 Population: 4000 GDP Per Capita: $43.75 GDP Per Capita: 43 Dollars and 75 Cents
I was able to cast gdpPerCapita and gdpPerCapitaDollars without an issue. The problem comes when trying to get the remainder (75). I have tried
int gdpPerCapitaCents = (int)gdpPerCapita - gdpPerCapitaDollars;
And
int gdpPerCapitaCents = (double)gdpPerCapita - gdpPerCapitaDollars;
And
int gdpPerCapitaCents = (int)gdpPerCapitaDollars - gdpPerCapita;
And lastly
int gdpPerCapitaCents = (double)gdpPerCapitaDollars - gdpPerCapita;
I'm sure I am just doing something slightly wrong here, as i have never tried to use arithmetic operators on casted variables. Uber confusion here, any help appreciated.