This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 6 years ago.
I'm currently doing an assignment for school, and I need to create a program that uses Math.random() to get a random value, and depending on the value, output "Heads" or "Tails". It needs to do this 10 times. Then, it needs to find the percentage of times that the program output heads, and how many it output tails. However, it isn't working correctly. It always outputs that heads/tails were 0% of the tosses. Can someone please explain why?
public class HeadsTails
{
public static void main(String[] args)
{
int v;
double i;
int heads = 0, tails = 0;
double headsPercent, tailsPercent;
for(v = 1; v <= 10; ++v)
{
i = Math.random();
if(i <= 0.5)
{
System.out.println("Heads");
heads = heads + 1;
}
else if(i > 0.5)
{
System.out.println("Tails");
tails = tails + 1;
}
}
headsPercent = (heads / 10) * 100;
tailsPercent = (tails / 10) * 100;
System.out.println("Heads were " + headsPercent + "% of the tosses.");
System.out.println("Tails were " + tailsPercent + "% of the tosses.");
}
}
I am also quite open to any improvements that can be made, besides those that just make the program function properly.
The problem is integer math. heads and tails are both int, so:
heads / 10
...yields an int result, which will almost always be 0 in your case because in int-land, 1 / 10, 2 / 10, through 9 / 10 are all 0. The only time you'd get anything else would be if all the rolls were heads or all were tails, where 10 / 10 is 1.
Cast to double before doing the math:
headsPercent = ((double)heads / 10) * 100;
tailsPercent = ((double)tails / 10) * 100;
Doing that fixes the problem.
Side note 1: You can add to a variable using +=, e.g.:
heads += x;
And of course, when what you're adding is 1, you can just use the increment operators, either prefix:
++heads;
or postfix
heads++;
(In terms of updating heads and tails, it doesn't matter which.)
Side note 2: You don't need else if (i > 0.5). If you think about the logic, you have if (i <= 0.5) ... else ... That means that i will definitely be > 0.5 once you get to the else, no need for the if (i > 0.5) part.
And if you do that, you don't even need i anymore:
for(v = 1; v <= 10; ++v)
{
if(Math.random() <= 0.5)
{
System.out.println("Heads");
++heads;
}
else
{
System.out.println("Tails");
++tails;
}
}
Related
I need something that can calculate the nearest highest multiple of 9. So for example, if I input 1 into this function it will return 9, if I input 10 into this function it will return 18 and so on.
I've tried this 9*(Math.round(number/9)) and 9*(Math.ceil(Math.abs(number/9))) but they return the nearest multiple of 9, so if you input 10 into this function it will return 9, for my purposes it will need to return 18. (There's probably a better way to say this other then "nearest highest")
If anyone can help me that will be great!
You can use this formula.
number + (9 - (number % 9))
And for the exceptional case when the number is a multiple of 9, use a condition:
int result = number % 9 == 0 ? number : number + (9 - (number % 9));
Just add one (max) 9 times and check if it is a multiple of 9 like so:
int x = 9;
int result = 0;
for (int i = x; i < 9; i++)
{
if (i % 9 == 0)
{
result = i;
break;
}
}
// result will contains the 'nearest' 'highest' or it self multiple of 9
You can try defining a multiplier whose value depends on whether number is multiple of 9 or not. Check below code:
int number = 10;
Double ceilValue = Math.ceil(number/9);
double multiplier = 0.0;
if (number % 9 == 0) {
multiplier = ceilValue;
} else {
multiplier = ceilValue + 1;
}
Double result = 9 * multiplier;
System.out.println(result);
Output:18.0
I am writing a program that will simulate a cash register change calculator. It should print the change and how to give back the change ( number of twenty, tens, fives, quarters, dimes, etc).
The problem is that when I compile the program, I get a big number. I've tried rounding it down but it doesn't work. ALSO, I don't know if it is caused by the change not being rounded but I won't get the number of cents, I only get 1 $10 bill.
p.s. I am taking a high school CS course and right now I can't use other methods of rounding it, I know there is a way like the one I attempted below (casting and stuff) which I am allowed to use at the moment.
Thank you.
public class changeCash
{
public static void main(String[] args)
{
double cost = 68.90;
double amtPaid = 80.00;
double change = 0;
int twentyBill= 0;
int tenBill = 0;
int fiveBill = 0;
int oneBill = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
change = amtPaid - cost;
change = ((int)change * 10) / 10.0;
System.out.println("Your change is " +"$" + change);
double back = amtPaid - cost;
if(back >= 20)
{
twentyBill++;
back -= 20;
System.out.println(twentyBill + " $20 bill(s)");
}
else if(back >= 10)
{
tenBill++;
back -= 10;
System.out.println(tenBill + " $10 bill(s)");
}
else if(back >= 5)
{
fiveBill++;
back -= 5;
System.out.println(fiveBill + " $5 bills(s)");
}
else if(back >= 1)
{
oneBill++;
back -= 1;
System.out.println(oneBill + " $1 bills(s)");
}
else if(back >= 0.25)
{
quarters++;
back -= 0.25;
System.out.println(quarters + " qaurter(s)");
}
else if(back >= 0.10)
{
dimes++;
back -= 0.10;
System.out.println(dimes + " dime(s)");
}
else if(back >= 0.05)
{
nickels++;
back -= 0.05;
System.out.println(nickels + " nickel(s)");
}
else if(back >= 0.01)
{
pennies++;
back -= 0.01;
System.out.println(pennies + " penny(ies)");
}
}
}
Couple of issues. First, smaller one:
change = amtPaid - cost;
Change is 11.1, as it should be, but then:
change = ((int)change * 10) / 10.0;
Casts take precedence over arithmetic, so first (int)change happens (which results in 11), then it is multiplied by 10, then divided by 10.0, and you end up with 11.0 instead of 11.1.
But your bigger problem is in your if statements. You have a series of if...else. Once one of these executes, the remainder of the else blocks will not. So when you have e.g.:
if (back >= 20) {
...
} else if (back >= 10) {
...
} else if (back >= 5) {
...
} else ...
As soon as one hits, it's done. If back >= 20 is false it goes to the next. Then if back >= 10 is true, it executes that, then doesn't execute the rest, so you would want to separate them, e.g.:
if (back >= 20) {
...
}
if (back >= 10) {
...
}
if (back >= 5) {
...
}
...
That'll get you closer, but you're still not quite there. For example, what if your change is 40? That will be two 20's. But your if statement will only take away a single 20. To that end, a while loop would be appropriate. It also more accurately reflects reality. In real life if you had to give somebody $40, you wouldn't just give them a single $20 and walk away, you'd get a dirty look. You'd keep giving them $20's until the amount you owed them was less than $20. So for example:
while (back >= 20) {
...
}
while (back >= 10) {
...
}
while (back >= 5) {
...
}
...
You want your code to reflect the logic you would use in reality.
Regarding your question in comments:
... why do I get $11.099999999999994 instead of just 11.1?
Floating-point rounding error. Decimal numbers are not 100% accurate; "11.1" can't be represented precisely. You have a couple of ways to work around it. You could round to two decimals when you display the number, e.g. System.out.printf("%.2f", change). However, you may want to use int and store the number of cents, rather than using double and storing the number of dollars. Working with integers is more precise, and actually, when working with currency in important applications, integers are often used for this reason.
Simpler Solution
double d = 2.99999999;
long l = (long) d;
Math.class, floor function
double d = Math.floor(2.55555) //result: 2.0
Returns the largest (closest to positive infinity) double value that
is less than or equal to the argument and is equal to a mathematical
integer
Find below the code which works well. Tested with different values. We want to avoid more than 2 decimal places hence I have added several utility methods just to do that.
Uncomment different cost values to see its working in different scenarios.
public class ChangeCash {
public static void main(String[] args) {
double cost = 65.90;
// cost = 68.33;
// cost = 42.27;
double amtPaid = 80.00;
double change = 0;
int twentyBill = 0;
int tenBill = 0;
int fiveBill = 0;
int oneBill = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
change = amtPaid - cost;
System.out.format("Your change is $ %.2f", decimalCeil(change, true));
System.out.println();
double back = decimalCeil(change, true);
if (back >= 20) {
twentyBill++;
back -= 20;
System.out.println(twentyBill + " $20 bill(s)");
}
if (back >= 10) {
tenBill++;
back -= 10;
System.out.println(tenBill + " $10 bill(s)");
}
if (back >= 5) {
fiveBill++;
back -= 5;
System.out.println(fiveBill + " $5 bills(s)");
}
if (back >= 1) {
oneBill = (int) (back * 10) / 10;
back -= oneBill;
System.out.println(oneBill + " $1 bills(s)");
}
if (decimalCeil(back) >= 0.25) {
quarters = (int) (back * 100) / 25;
back = correct2DecimalPlaces(back, 25);
System.out.println(quarters + " qaurter(s)");
}
back = (int) (decimalCeil(back, true) * 100);
if (back >= 10) {
dimes = (int) (back / 10);
back = back % 10;
System.out.println(dimes + " dime(s)");
}
if (back >= 5) {
nickels = (int) (back / 5);
back = back % 5;
System.out.println(nickels + " nickel(s)");
}
if (back >= 1) {
pennies = (int) back;
System.out.println(pennies + " penny(s)");
}
}
private static double correct2DecimalPlaces(double back, int modulo) {
int correctTwoPlaces = (int) (back * 100) % modulo;
back = (double) correctTwoPlaces / 100;
return back;
}
private static double decimalCeil(double change) {
int temp = (int) (change * 100);
double tempWithCeil = Math.ceil(temp);
double answer = tempWithCeil / 100;
return answer;
}
private static double decimalCeil(double change, boolean decimalThreePlaces) {
double temp = change * 1000;
double tempWithCeil = Math.ceil(temp);
double answer = tempWithCeil / 1000;
return answer;
}
}
I'm trying to create two separate outputs of 10 columns and 10 rows of numbers. I know I can do the first output using numbers 4 through 7 and the second output using numbers 10 through 90. But I have in trouble to do the third output using numbers 901 through 999. Below is the Java code I have:
import java.util.Random;
public class LabRandom
{
private static final Random rand = new Random();
public static void main(String[] args)
{
int number;
int i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(4) + 4);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(9)*10+10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(100)*10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
}
}
I'm having trouble understanding what you want. If you want to create an output of 100 randomly chosen number in the range 900 to 999, with line breaks after every 10 such numbers, try adding this loop to your code:
i = 1;
while (i <= 100)
{
// generate a random number from 0 to 100-1,
// then add 900 to transform the range to 900 to 999
System.out.printf("%-5d", rand.nextInt(100) + 900);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
By the way, if you really want to print numbers 10 to 90, your second loop is incorrect.
Right now you print multiples of 10, from 10 to 90, eg 10,20,30.....90
For every number between, you would want:
rand.nextInt(80)+10
// difference between the highest and the lowest value you want to have in your result
int range = 99;
// the lowest possible value you want to see in your result
int lowestValue = 901;
//note that you will never get the numbers 900 and 1000 this way, only between
int result = rand.nextInt(range) + lowestValue;
You might want to read what exactly nextInt(value) does (easy to do inside a proper IDE since it will provide JavaDoc tooltip, which is of course available and well detailed in such general Java classes).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given a range of integers, how do I generate a random integer divisible by 5 in that range?
I'm using Java
just generate a regular random integer and multiply it by 5!
details: generate a random integer in [0, n) where n is the number of multiples of 5 in your range, then multiply it by 5 and add the lowest multiple to it.
one-liner: System.out.println(rnd.nextInt(max / 5 - (min + 4) / 5 + 1) * 5 + (min + 4) / 5 * 5); (assuming non-negative and valid arguments)
credits: lowest multiple expression (min + 4) / 5 * 5 from here and expression simplified a bit based on #Thomas's (imo currently incorrect) answer
This question calls for a multiple of five in a range, not number in the period of five in the range.
This solution handles negatives and range validity.
// because Java's % operator doesn't do what one might expect with negatives
int lbound = (min+4) - (((min+4) % 5) + 5) % 5;
int ubound = max - (((max % 5) + 5) % 5);
if (lbound > ubound) {
// do something about the range error
}
if (lbound == ubound) {
return lbound;
}
int range = ((ubound - lbound)/5) + 1;
return ((int)(Math.random() * range) * 5) + lbound;
First create a Random, and round low and high to the nearest higher/lower multiple of 5 respectively:
Random r = new Random();
low = ((low+4)/5)*5; // next multiple of 5
high = (high/5)*5; // previous multiple of 5
This may make low > high, which is infeasible, so don't proceed any further; or it make may make low == high, which may be of no interest whatsover, so you may want to test for that. The code below works correctly either way, because of the +1 and -1: generate a random number in {low..high}
int randomPart = r.nextInt(high-low+1)+low-1;
Then round it upwards to a multiple of 5. The prior shenanigans with low and high assure it is in range:
int nextInt = ((randomPart+4)/5)*5;
This method first computes how many numbers divisible by 5 are in the given range. It picks a number between 0 and that count at random, and translates that random number back into the given range by multiplying it with 5 and adding it to the lower bound.
Note that both lowerBound and upperBound are inclusive.
public static int getRandomDivisibleByFive(int lowerBound, int upperBound) {
if (lowerBound > 0) lowerBound += 4;
if (upperBound < 0) upperBound -= 4;
lowerBound /= 5;
upperBound /= 5;
int n = upperBound - lowerBound + 1;
if (n < 1) {
throw new IllegalArgumentException("Range too small");
}
return 5 * (lowerBound + new Random().nextInt(n));
}
Picks a random number between your values and then tests if it is divisible by div. If it is it returns that value otherwise it will have to do at max div-1 iterations to get to a number divisible by div.
In your situation call rBetweenGenerator(min, max, 5)
public int rBetweenGenerator(int min, int max, int div)
{
int res = min + ((new Random()).nextInt(max - min + 1))
for(int i = res; i < res + div; i++)
{
if( i % div == 0 )
{
return i;
}
} return -1; //error
}
Here's how it's written in the book:
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
Write a program that takes a value x as input and outputs this sum for n taken to be each of the values 1 to 10, 50, and 100. Your program should repeat the calculation for new values of x until the user says she or he is through. The expression n! is called the factorial of n and is defined as
n! = 1*2*3*...*n
Use variables of type double to store the factorials (or arrange your calculation to avoid any direct calculation of factorials); otherwise, you are likely to produce integer overflow, that is, integers larger than Java allows."
I don't have any coding problems (not yet at least), my problem is I don't know what it's asking me to do. I get the factorial part (ex. 3i = 1*2*3) but I am just not sure what else it is asking. I have the user input a value for "x" but where does the "n" come from?
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
" I don't know what this is saying or asking for.
I put together this for loop for the 1-10, 50, 100 part and I don't know if that even makes sense without understanding the rest, but here it is:
for (counter = 1 ; counter <= 100 ;counter++)
{
//System.out.print("Enter value for x: ");
//x = keyIn.nextDouble();
if (counter >= 1 && counter <= 10)
{
if (counter == 1)
System.out.println("Iterations 1-10: ");
System.out.println("test to see if 10 show up");
}
else if (counter == 50)
{
System.out.println("Iteration 50: ");
}
else if (counter == 100)
{
System.out.println("Iteration 100: ");
}
}
I haven't been in algebra in about two years so some of this stuff is throwing me off a bit. Please help with whatever you can, thanks.
It's saying that e^x can be approximated through a Taylor Series: Sum(i:0:n)(xi/fact(i))
So, we have:
double ex_taylor_series(double x, int n)
{
double value;
for(int i = 0; i < n; i++)
{
value += Math.pow(x, i)/(factorial(i));
}
return value;
}
private int factorial (int num)
{
int value = 1;
for(int i = num; i > 1; i--)
{
value *= i;
}
return value;
}
In your case, you would simply feed different values of n, 10, 50 and 100, to ex_taylor_series.