PDA

View Full Version : Finding the average of random numbers a user inputs


haha123456
Oct 16, 2013, 04:01 PM
Here's my code. How do I get the output average when the user enters the random numbers. I keep getting 0.0 for the average.
Package averages;
import java.util.Scanner;
/**
*
* @author Kramer1
*/
Public class Averages {

/**
* @param args the command line arguments
*/
Public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);

Double sum = 0;
int count = 0;
Double input = 0;
System.out.println("Enter in as many numbers as you want and the average will be calculated: ");
Do{

System.out.print ("Please enter a number and when finished type a -1 to stop: ");
input = in.nextDouble();

}
While (input != -1);
Count++;

if (input != -1){
Sum = (input + sum);
Double average = sum / count;

System.out.println("Average of the numbers is " + average);
}else{
System.out.println("No Data.");
}



}
}

Celine91
Oct 17, 2013, 09:55 AM
This can be the c++ version of your code, it successfully calculates the average of random numbers the user inputs and terminates for -1 * as specified in your code*
---------------------------------------------------------------------
#include <iostream>
using namespace std;
int main()
{
int input;
double sum = 0;
int count = 0;

cout<<"Enter the numbers to which you want their average calculated:"<<endl;
cout<<"Enter -1 in order to terminate input! "<<endl;
do
{
cin>>input;
if (input == -1) break;
sum= sum + input;

count ++;
}while (input > 0);

cout<<" The average of the numbers is: "<<sum/count <<endl;


return 0;
}
-------------------------------------------------------