Average incorrect : decimal point always .0 [duplicate] - java

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 5 years ago.
I'm pretty new to arrays and am trying to create a simple program that calculates the average of 5 numbers. However, when the average is calculated, it always has a decimal point of 0 rather than what it should be, but I'm not sure why..
For example, if I type in 4, 4, 4, 4, 3, it displays 3.0 as the average rather than 3.8. Please help!
int[] boxes = new int[5];
for (int i = 1 ; i <= 5 ; i++)
{
System.out.print("Enter number " + i + " > ");
int n = Integer.parseInt(kb.nextLine());
boxes[i-1] = n;
}
double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;
System.out.println("The average of those five numbers is: " + mean);
Thank you!! :)

it is because the operation is done with integers , change your 5 to 5.0

I cannot answer you the specifics but there is a huge topic in java called type casting. I reckon, you read it. This is a good puzzle for you to solve yourself. Reminds me of my past :)

Fast fix: change 5 -> 5.0D.
Why? Let's look at dividing process more detail:
You get sum from all numbers: ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ), result -> int.
You divide sum(int type) / 5(int type) = result also int type 3.8 -> 3.
Last one its autocast int -> double.
That's why you get what you see.

Solution 1 :
- You can use 5.0 instead of 5 to have a double division.like that:
double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5.0;
Solution 2 :
- You can use a double cast of your sum like that:
double mean = (double)( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;
To improve your answer:
You can use int n=kb.nextInt(); instead of int n = Integer.parseInt(kb.nextLine());
You can count the sum in for loop like that:
int[] boxes = new int[5];
int sum=0;
for (int i = 1 ; i <= 5 ; i++)
{
System.out.print("Enter number " + i + " > ");
int n=kb.nextInt();
boxes[i-1] = n;
sum +=boxes[i-1];
}
double mean = sum / 5.0;
System.out.println("The average of those five numbers is: " + mean);

Related

how to get double to round up to nearest integer?

the prompt says "Write a program which takes two doubles as input, then prints the sum of the numbers when they are both rounded to their nearest whole number. You may assume the double input is always positive."
what i wrote:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble();
double hit_2 = scan.nextDouble();
double hit_add = (hit_1 + hit_2 + 0.5);
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + (int)hit_add);
for most decimals, it rounds fine, but what i want is for numbers like 4.5 to round to 5. right now, it rounds 4.5 to 4. i added 0.5 in an attempt to get the double to round up, but it didn't work. i'm also not allowed to use Math.round() or anything like that.
create your own round method like this.
Convert to int, then find the remainder.
If remainder >= 0.5, just add 1 to the integer. See below:
private static int round(double d){
int i = (int)d;
double remainder = d - i;
if(remainder>=0.5){
i++;
}
return i;
}
then you can use that method on your double
just need +0.5:
double a = 1.8, b = 1.2;
System.out.println((int)(a + 0.5));
System.out.println((int)(b + 0.5));
System.out.println((int)(a + 0.5) + (int)(b + 0.5));
for your code:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble() + 0.5;
double hit_2 = scan.nextDouble() + 0.5;
int hit_1P2 = (int)hit_1 + (int)hit_2;
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + hit_1P2);
There was two ways where double can be rounded off to nearest integer.
a. Using typecasting to int
Example : If double holds value as 3.26, all the digits after decimal are lost.
b. Using Math.round() function - This will add 0.5 to double and rounds to nearest integer.
Example : If double holds value of 3.7, then this function will add 0.5 and rounds to 4 as nearest integer.
Similar way, if double value is 3.2, then Math.round() will add 0.5, so this would become 3.7, in this case the nearest integer is still 3
Below is sample code block for above two examples
double d = 3.5;
int typeCastInt = (int) d;
int t = (int) Math.round(d);
System.out.println(typeCastInt); //prints 3
System.out.println(t); //Prints 4

My program does not output the right decimal numbers of an arithmetic average. How can I fix it?

I need to display the correct arithmetic average of a series of integers entered by the user.
If the user enters 6, 9, 7, and 4, the average should be 6.5 but instead displays 6.0. Why does that happen? I used an ArrayList to store all the integers.
import java.util.Scanner;
import java.util.*;
import java.util.Collections;
public class QuizScoreStatistics
{
public static void main(String[] args) {
List<Integer> Scores = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
int i = 0;
int a = 0;
while(a != 99) {
System.out.println("Enter scores");
a = input.nextInt();
if(a != 99) {
if ( a > 10 || a < 0) {
System.out.println("Score must be between 10 and 0");
}
else {
Scores.add(a);
}
i++;
}
}
int max = Collections.max(Scores);
int min = Collections.min(Scores);
int sum = 0;
double averg = 0;
for( i = 0; i <= Scores.size() - 1; i++) {
sum += Scores.get(i);
}
averg = sum / Scores.size();
System.out.println("Scores entered " + i);
System.out.println("Highest score " + max);
System.out.println("Lowest score "+ min);
System.out.println("Average: "+ averg);
}
}
I won't try to give away the entire question I think you could probably answer that yourself given a nudge in the right direction.
You correctly identified that your averg is a double because your answer could come out to something like 6.7 or 2.3 or whatever. Thats a correct assumption to make! However during your "arithmetic process" you are using integers to do the division, which will come out as an integer. I will repeat the actual DIVISION is happening with two integers , can you see where the bug is coming from?
If you need more of a push to see the exact remedy of this solution I would point you here
https://programming.guide/java/wrong-results-for-division.html
Try averg = (1.0 *sum) / Scores.size(); because int/int => int but double/int=>double
Ok, this is how the operator "/" works.
int / int => int
int / float => float
float / int => float
Since you are doing an int division (int/int), the result will be an int, losing decimal information. If you want your division to be float or double, you have two options, either you declare the sum as double or you can just cast the division, so it becomes a double division instead of an int division.
averg = (double) sum / Scores.size();

Splitting units base of a number and separating remainders

I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!

Incorrect subtraction results: 3.999999, not 4 [duplicate]

This question already has answers here:
Adding and subtracting doubles are giving strange results [duplicate]
(2 answers)
Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?
(14 answers)
Closed 9 years ago.
So I narrowed down a bug in my application to java messing up a simple subtraction calculation. I can't figure out why exactly. Here is the bit of code:
for (double x = (((double)bdl.length())-1)/10; x > 0; x--) {
int count;
System.out.println("x = " + x);
if (x >= 1) {
System.out.println("X = " + x + " so count = 20");
count = (20);
} else {
count = (int)(x*20);
System.out.println("X = " + x + " so count = "+count);
}
}
The variable bdl is just a JSONArray, which I am only concerned with its length at this point. As bdl comes in initially it has length 15, so x will equal 1.4 . The first time through the loop the first println says "X = 1.4 so count = 20" which is correct. The second time through however when x should = 0.4, it instead says "X = 0.3999999999999999 so count = 7". I understand that casting (x*20) to an int at that point and time will give me 7, but my question is Why is x not equal to 0.4 .
You're using a double, which is a floating-point number. This is not meant for presision, moreover, it is meant for speed and non-precision. So instead, you should be using an int, like this:
for (int x = ((bdl.length())-1)/10; x > 0; x--) {
This will keep your numbers precise.
Actually, your 'x' does equal 0.4, it's only a matter of precision.
All floating point comparison operations should be executed with a certain precision (delta or epsilon in some implementations).
Refer to this post.

IndexOutOfBounds, but why?

I'm writing an app's code and when I enter only 2 numbers I get indexoutofbounds Length=2 Index=2. Why is this/how can I circumvent it?
Here is my code:
Arrays.sort(newNums);
double median = 0;
if(newNums.length%2!=0){
median = (double) newNums[newNums.length/2];
}else if(newNums.length%2==0){
median = ( (double) newNums[newNums.length/2 + 1] + (double) newNums[newNums.length/2-1] )/2;
}else{
}
String medianString = Double.toString(median);
showDialog(medianString, type,"Median:");
newNums.length/2 + 1 == 2 for newNums.lenght == 2
You probably don't want + 1 there to sum two values on the indexes next to each other.
Array indexes in Java start from 0. This expression newNums[newNums.length/2 + 1] will throw ArrayIndexOutOfBoundsException if the size of the array is 2.
The erros is:
median = ( (double) newNums[newNums.length/2 + 1] + (double) newNums[newNums.length/2-1] )/2;
When newNums.length == 2, this will result in IndexOutOfBoundError.
Also, the median of a even length array is the average of two consecutive middle elements, but your code gives the average of middle + 1 and middle - 1 elements.
Instead, use this:
median = ( (double) newNums[newNums.length/2] + (double) newNums[newNums.length/2-1] )/2;

Categories