Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Practice MT2: Q12 (average temperature)

+8 votes

What answer did you get for this one?

(Again, you can use the <> "add code" button to add better-formatted Java code to your Q&A answers.)

asked Jan 25, 2015 in (Winter 14) by Forrest Stonedahl (3,438 points)

2 Answers

+2 votes

	
	public static void main(String[] args) {
		Scanner console = new Scanner(System.in);
	    	
		System.out.print("Enter the number of temps: ");
		int numTemps = console.nextInt();
	    	
		double sum = 0;
		int highTemp = 0;
	    	
		for (int i = 1; i <= numTemps; i++) {
			System.out.print("Next temp: ");
			int temp = console.nextInt();
				
	    	sum += temp;
	    	
	    	//HELP! I cannot figure out the high temp when dealing
	    	//with negative and positive numbers. This is what I have
	    	//so far.
	    	if(temp > highTemp) {
	    			highTemp = temp;
	    	} else if (temp < highTemp) {
	    		highTemp = Math.min(Math.abs(temp), highTemp);
	    	}
	    }
	    	
	    double avgTemp = sum/numTemps;
	    
	    System.out.println("");
	    System.out.println("Average temp: " + avgTemp);
	    System.out.println("Highest temp: " + highTemp);
	    }

 

answered Jan 26, 2015 by Lauren Johnson (100 points)
Please clarify -- is this an answer, or more of a question / call for help?
0 votes
public static void main(String[] args) {
		Scanner console = new Scanner(System.in);
	    	
		System.out.print("Enter the number of temps: ");
		int numTemps = console.nextInt();
	    	
		double sum = 0;
		int highTemp = -Integer.MAX_VALUE;  //highTemp can also be a very
		                                    //large neg number.
	    	
		for (int i = 1; i <= numTemps; i++) {
			System.out.print("Next temp: ");
			int temp = console.nextInt();
				
	    	sum += temp;
	    	
	    	if(temp > highTemp) {
	    			highTemp = temp;
	    	} 
	    }
	    	
	    double avgTemp = sum/numTemps;
	    
	    System.out.println("");
	    System.out.println("Average temp: " + avgTemp);
	    System.out.println("Highest temp: " + highTemp);
	    }

 

answered Jan 26, 2015 by Lauren Johnson (100 points)
Can you explain a little more -- is this answer one that you think is correct?
I think this is the answer.  However, I was looking to see if anyone had anything different as well.
I haven't thoroughly tested your code, but it looks good at glance.  A few comments...

* Integer.MIN_VALUE would be a better choice than -Integer.MAX_VALUE
(actually any number smaller than -460 should be fine to initialize highTemp with, since temperatures cannot go below absolute zero!)

* Note that having the sum variable be a double is important, so that (sum / numTemps) uses double division, instead of integer division, to compute the average.  (You did this right, although of course there are multiple ways it could be done.)
...