I want to start off saying that I'm new at this. I'm trying to make a for loop that will Show me the different 40 yard dash times converted into MPH. The problem is output that's being shown:
5.96 40 Time is 13.727882855399633 Miles Per Hour
6.96 40 Time is 11.755485893416928 Miles Per Hour
7.96 40 Time is 10.27866605756053 Miles Per Hour
I want it to show as 5.96, 5.97, 5.98, etc instead of 5.96 and 6.96.
Does anyone understand what I'm trying to do as well as to fix this problem I'm having?
public class FortyToMPH {
public static void main (String args []) {
double yards, foot, FeetInMiles, SecondsPerHour,FeetLength;
double FortyTime, Minutes, SecondsPerMile, MPH;
int counter;
counter = 0;
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) {
yards = 40; // length in yards
foot = yards * 3; // convert to feet
System.out.println();
FeetInMiles = 5280; // The number of feet in a Mile
SecondsPerHour = 3600;
FeetLength = FeetInMiles / foot; // You divide the Feet in Miles by the feet conversion of 40 yards
System.out.println();
SecondsPerMile = FeetLength * FortyTime;
MPH = SecondsPerHour / SecondsPerMile;
System.out.println(FortyTime + " 40 Time is " + MPH + " Miles Per Hour ");
counter++;
// every 10th line, print a blank line
if(counter == 10) {
System.out.println();
counter = 0; // reset the line counter
}
}
}
}
The problem is that you're using the ++ operator in your for loop definition:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) {
Change the for loop to a while loop that includes a line incrementing FortyTime by 0.01 each loop:
while(FortyTime <= 7.99) {
FortyTime += 0.01;
// execute the rest of your code here
}
MarounMaroun rightfully pointed out that using a double as a loop counter runs the risk of nasty floating-point arithmetic errors, so I've changed the for loop to a while loop.
The ++ operator means "reassign the value of x as x + 1." It'll only give you increments (or decrements, with --) of 1.
Note that this is going to print out hundreds of lines before it completes.
I would recommend you to use int in your loop and perform all calculations of doubles inside the loop to prevent problems with floating point arithmetic:
for(int i = 0; i < something; i++) {
double fortyTime = 4.96 + i;
//...
}
Also please pay attention to Java Naming Conventions and rename your variables.
To demonstrate problems of floating point arithmetic, try this loop:
for(double i = 0; i < 1.0; i += 0.1)
System.out.println(i);
This will print
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
And you don't want output like this in your program.
Here I modified the code you gave to print doubles as a two decimal place numbers (see format %.2f) produced in the loop while (the step for the loop is defined in DELTA variable).
public class FortyToMPH
{
public static void main (String args [])
{
double yards, foot, feetLength;
double fortyTime = 4.96, minutes, secondsPerMile, mph;
int counter = 0;
/**
* Constants.
*/
final double FEET_IN_MILES = 5280;
final double SECONDS_PER_HOUR = 3600;
final double DELTA = 0.01;
final double END = 7.99;
while (fortyTime <= END)
{
yards = 40; // length in yards
foot = yards * 3; // convert to feet
feetLength = FEET_IN_MILES / foot; // You divide the Feet in Miles by the feet conversion of 40 yards
secondsPerMile = feetLength * fortyTime;
mph = SECONDS_PER_HOUR / secondsPerMile;
System.out.format("%.2f 40 Time is %.2f Miles Per Hour%n", fortyTime, mph);
counter++;
// every 10th line, print a blank line
if(counter == 10) {
System.out.println();
counter = 0; // reset the line counter
}
fortyTime += DELTA;
}
}
}
just change the for loop like this:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime=FortyTime+.01)
and print it like
System.out.println((float)FortyTime + " 40 Time is " + MPH + " Miles Per Hour ");
You need to make two changes:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime=FortyTime+0.01)
So that the FortyTime is incremented by 0.01 and not 1 and
System.out.printf("%.2f 40 Time is %f Miles Per Hour ", FortyTime, MPH);
So that it prints in correct precision.
Related
For a class that I am taking I am trying to create a program that produces a table of sin(), cos(), and tan() values for angles from 0 to 180 degrees in steps of 5 degrees.
!http://i65.tinypic.com/14ahliq.jpg
So far I have the following code, which produces an introduction and the first two lines of the table, but I cannot figure out how to get it to repeat.
import java.util.*;
public class Angles {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("This program computes the");
System.out.println("sin(), cos(), and tan() values");
System.out.println("for angles from 0 to 180 degrees");
System.out.println("in steps of 5 degrees.");
System.out.println("");
System.out.println("Angle\tSin()\tCos()\tTan()");
double Anglex = 0;
for(double i = 5;i <= Anglex;i += 5) {
Anglex = 0 + i;
}
double Sinx = Math.sin(Math.toRadians(Anglex));
double Cosx = Math.cos(Math.toRadians(Anglex));
double Tanx = Math.tan(Math.toRadians(Anglex));
System.out.println(Anglex + "\t" + Sinx + "\t" + Cosx + "\t" + Tanx);
}
}
Is not really ok that you ask people on forums to solve your assignments.
Otherwise, several issues with your little program (didn't test, please do it yourself).
anglex should start at 0 and stop at 180. So for(int anglex=0; anglex<=180; anglex+=5). Use anglex instead of i, inside the loop.
the calculations for sinx, cosx, tanx and the printing of the new line should be inside the curlies {}. As your code is right now, the only thing inside the loop is the increment of anglex.
Sorry for not providing the full solution, pretty sure you can do it.
Recast your for loop to
for (double Anglex = 0; Anglex <= 180; Anglex += 5){
Note well the opening brace to enclose multiple subsequent statements. Don't forget to balance it with a closing }; probably after the println call.
Using a double as a loop index is not to everyone's taste (you can get yourself into trouble if you are not using whole numbers), but this is fine in this instance, particularly also as you are using <= as the stopping condition.
Starting variable names with an upper case letter is also to be discouraged in Java as it's unconventional.
Your for loop only applies on the Anglex = 0+i line.
Add {} to the whole section that should be repeated.
public static void main(String[] args) {
System.out.println("This program computes the");
System.out.println("sin(), cos(), and tan() values");
System.out.println("for angles from 0 to 180 degrees");
System.out.println("in steps of 5 degrees.");
System.out.println("");
System.out.println("Angle\tSin()\tCos()\tTan()");
double maxAngleX = 180.0;
for (double angleX = 5; angleX <= maxAngleX; angleX += 5) {
double Sinx = Math.sin(Math.toRadians(angleX));
double Cosx = Math.cos(Math.toRadians(angleX));
double Tanx = Math.tan(Math.toRadians(angleX));
System.out.println(angleX + "\t" + Sinx + "\t" + Cosx + "\t" + Tanx);
}
}
for(double i = 5;i <= Anglex;i += 5) {
Anglex = 0 + i;
double Sinx = Math.sin(Math.toRadians(Anglex));
double Cosx = Math.cos(Math.toRadians(Anglex));
double Tanx = Math.tan(Math.toRadians(Anglex));
}
Enclose the above statements inside a { and }. The for loop applies for only the first statement in your code.
I have an assignment where I am supposed to determine whether the average of three values is 'above average' or 'below average'. For some reason whatever is input will always be above average as the result. Here is my code below, thank you for any help!
import java.util.Scanner;
class Lesson_12_Activity_One {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter three values");
double x = scan.nextDouble();
double y = scan.nextDouble();
double z = scan.nextDouble();
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}
}
The average is t/100 but in your condition you test if t > 89.5 (which is always true since t is the average multiplied by 100).
Just remove both the multiplication by 100 and the division by 100. They don't seem necessary.
double t = Math.round((x+y+z)/3);
System.out.print("The average is " + t);
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}
if(t/100 >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
by the way why are you multiplying and then dividing by 100?
I'm gonna guess that you're mixing up perunages and percentages. That means, at one point in your program you use 0.5 and in the other 50, both as 50%.
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
With x, y and z all as 50, this will output 50. t = 100 * (50 + 50 + 50)/3 = 5000, the output is (t/100) = 50.
if(t >= 89.5) however tests with t = 5000.
To solve this, go down one of two paths.
Replace all percentages for perunages. This means inputting numbers from 0 to 1.
To do this, do the following:
change your t-initialization for double t = (double)Math.round(1000*((x+y+z)/3)) / 1000 This will make T be in between 0 and 1 with 3 digits precision.
Replace your if with if (t >= 0.895)
Replace all perunages with percentages. This means inputting numbers from 0 to 100.
To do this, remove the 100* from your double t = (double)Math.round(100*((x+y+z)/3));, and the /100 from the output message.
So here is my task:
A postal company for a package charges $15 for the first
pound or a fraction thereof and $10 per pound for anything over one
pound. Write a program that prints the charge of a package.
Variables:
weight
First execution:
Weight? -12 Weight must be a positive number.
Second Execution:
Weight? 0 Weight must be a positive number.
Third Execution:
Weight? 2 Pay: $25.00
Forth Execution:
Weight? 2.8 Pay: $33.00
Fifth Execution:
Weight? 2.07 Pay: $25.70
and Here is the code I have developed so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
for (double i = 1; i < weight; i = i + .01) {
if (weight > 1) {
output = output + (1 / 10.00);
}
}
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
Everything works, but what I can't figure out is why (especially in the Fourth and Fifth Execution) is the final output always .10 cents off. Can anyone help me get to the accuracy I need?
Here is what I came up with:
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else {
// Print the charge of the package
if (weight > 1) {
output = cost + ((weight-1) * 10);
} else {
output = cost;
}
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
This should handle all of your cases, as well as numbers between 0 and 1 assuming it's $1 per 0.1 lbs. Instead of your for-loop, you can just use the cost + ((weight-1) * 10) formula. I removed the check to see if weight was equal to 1 because it's handled in the else clause.
If I understand the question correctly, you should never have any fractional dollar amount because anything over a pound is automatically rounded up to the next pound. ie: 2.01 lbs would become 3 lbs. If this is correct, then you could use Math's ceil function to round the weight up to the nearest whole pound, then do something like this:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
double temp = (Math.ceil(weight)) - 1;
for(double i = temp; i > 0; i-- ) {
output += 10;
}
output += cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
This way, you don't need to bother with 10 cent increments. I hope this helps. Let me know if you have any questions.
This: double i = 1; i < weight; i = i + .01 could be your problem.
Doubles are not exact for decimal math. You're expecting i == weight, at which point the loop should stop, but it might not because i + .01 (however many times) is a tiny fraction less than weight.
My advice is to ditch the loop. If the package is over 1 lb, just subtract one pound from the weight, multiply by the $10 per pound, and then round to the two decimal places you need (NOTE: round it according to how it's spec'd to be rounded, don't just let the conversion from double to decimal do it on its own. There are multiple ways to round something, and decimal does not magically know which one is right for your problem.)
EDIT: Look at your solution, is it supposed to only work to a resolution of 1/10 of a lb? If so, start by rounding the weight. Again, round it according to how it needs to be rounded (down, up, or nearest).
I'm working on a big program that utilizes a bunch of smaller methods to create a functioning auction system. I'm having trouble with this particular method where I have to raise the minimum bid for an item given the current or "now highest bid"
The instructions are as follows:
If a bid is accepted, then you need to raise the minBid on that item by 5% above the current bid,rounded up to the nearest $5 below $100.00,
rounded up to the nearest $10 between $100.01 and
$1000.00, rounded up to the nearest $50.00 between
$1000.01 and $10000.00, and rounded up to
the nearest $100 above $10000.00
My main issue is figuring out exactly I can round up by just 5 or just 10, depending on the amount of the bid. Here's my code so far, any help would be greatly appreciated :)
public class computeMinNextBid
{
public static double computeMinNextBid(double currentBid)
{
double minNextBid = (currentBid * 0.05) + currentBid;
if(minNextBid <= 100.00)
{
minNextBid = Math.round(minNextBid);
}
else if(minNextBid >= 100.01 && minNextBid <= 1000.00)
{
minNextBid = Math.round(minNextBid);
}
else if(minNext Bid >=1000.01 && <= 10000.00)
{
minNextBid = Math.round(minNextBid);
}
else(minNextBid >= 10000.01)
{
minNextBid = Math.round(minNextBid);
}
return minNextBid;
}
public static void main(String [] args)
{
double currentBid = Double.parseDouble(args[0]);
double minNextBid = computeMinNextBid(currentBid);
System.out.println("The next minimum bid is: " + minNextBid);
}
}
The general expression for rounding to N (using integer arithmetic) is:
x = (x + N/2)/N * N;
This rounds to the nearest multiple of N. For example, for x = 45 an N = 100, this yields 0 (i.e., it rounds 45 down to 0). For x = 55, this yields 100 (i.e., it rounds 55 up to 100).
To round down (also known as truncation), remove the "+ N/2" part:
x = x/N * N;
To round up to the nearest N, use:
x = (x + N-1)/N * N;
For example, for x = 35 and N = 100, this yields 100 (i.e., it rounds any x between 0 and 99 up to 100).
I am new to java, and my program is likely nowhere near as efficient as it could be, but here it is:
public class Compute {
public static void main(String[] args) {
for(double i = 10000; i <= 100000; i += 10000)
{
System.out.println("The value for the series when i = " + i + " is " + e(i));
}
}
public static double e(double input) {
double e = 0;
for(double i = 0; i <= input; i++)
{
e += 1 / factorial(input);
}
return e;
}
public static double factorial(double input) {
double factorial = 1;
for(int i = 1; i <= input; i++)
{
factorial *= i;
}
return factorial;
}
}
I believe this calculates the value e for i = 10000, 20000, ..., & 100000.
Where e = 1 + (1/1!) + (2/2!) + ... + (1/i!)
It takes about 47 seconds to do so, but I believe it works.
My issue is, for every i, the result is always 0.0
I believe this is because whenever the method factorial is called, the return value is too big to be stored which somehow causes a problem.
What can I do to store the value returned by the method Factorial?
Although you can calculate arbitrary precision results with BigDecimal, there is no need to calculate to 100000! for the series expansion of e. Consider that the 20th term in the series (20/20!) has a magnitude of about 10-19, so its contribution to the overall total is insignificant.
In other words, the contribution of any terms after the 20th would change only digits after the 19th decimal place.
You should probably use java.math.BigInteger to store the factorial.
Change this
e += 1 / factorial(input);
to
e += 1 / factorial(i);
Lots to do to speed up the code. Think about (i+1)! vs i!, don't recalc the whole factorial every time.
Also stop calculating when the answer will change less than the required precision like Jim said.