# Thread: code help

1. Member
Join Date
Sep 2011
Posts
69
Rep Power
0

## code help

hi i have got this code and i got it to equal 2000 but i need it to equal 1000 can somebody please help me

many thanks..

/calculate and output half of my savings
public class Savings
{
//your share is 50% of my savings
public static void main (String args[])
{
int mySavings = 2000;
int yourPercentage = 50;

int yourShare = (mySavings + (yourPercentage / 100));

System.out.println("Your share: " + yourShare);
}
}

2. ## Re: code help

Multiplication is used to find a percentage of some number, not addition.

3. Member
Join Date
Sep 2011
Posts
69
Rep Power
0

## Re: code help

i put in * m8 and i got an answer of 0?

4. Member
Join Date
Oct 2011
Location
Washington State
Posts
8
Rep Power
0

## Re: code help

Try replacing your code:

int yourShare = (mySavings + (yourPercentage / 100));

with:

int yourShare = (mySavings * (yourPercentage / 100));

your code should produce 2000.5 This code produces 1000.

Golfnut

5. Member
Join Date
Sep 2011
Posts
69
Rep Power
0

## Re: code help

//calculate and output half of my savings
public class Savings
{
//your share is 50% of my savings
public static void main (String args[])
{
int mySavings = 2000;
int yourPercentage = 50;

int yourShare = (mySavings*(yourPercentage / 100));

System.out.println("Your share: " + yourShare);
}
}

this is the code and i am still getting 0 as my answer

6. Senior Member
Join Date
Jan 2011
Location
Posts
270
Rep Power
4

## Re: code help

A hint:

what is an Integer from 50 / 100?
Last edited by milovan; 10-07-2011 at 01:19 AM. Reason: better example

7. Member
Join Date
Oct 2011
Location
Washington State
Posts
8
Rep Power
0

## Re: code help

Duh. Not sure if this would be the preferred way to go about this, but this works:

double mySavings = 2000;
double yourPercentage = 50;
double yourShare = mySavings * (yourPercentage / 100);

System.out.println("Your share: " + yourShare);
}
}

8. ## Re: code help

It has to do with how integer division works. Integer division uses truncation of the remainder. If you divide 9 by 5, you get 1.8, but integer division truncates the decimal part. You would get 1 as an answer. While Golfnut tests solution works (side note to golfnut -- don't spoon feed, and use code tags [code] YOUR CODE HERE [/code]), sometimes it's not feasible to have everything be an integer. In this case you can cast one of the numbers to a floating point form (double or float). Integer division only occurs with 2 integers, if there exists one non integer, the compiler will handle everything for you.

Java Code:
`(double) 5 / 2;`
is fine in most cases.
Last edited by sunde887; 10-07-2011 at 05:21 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•