Write a function total_numbers(number_list,weights) that takes a list of numbers
ID: 3808996 • Letter: W
Question
Write a function total_numbers(number_list,weights) that takes a list of numbers and their weights and returns the weighted total of the numbers. Think about what needs to happen before using a loop, during the loop, and after the loop finishes. In this question you are required to use a for loop, and not allowed to use the sum function. If the numbers are [1,2,3] and the weights are [.1,.5,.4] then the weighted total should be 1 * .1 + 2 * .5 + 3 * .4 = 2.3
For example:
Test Result print(round(total_numbers([1,2,3],[.1,.5,.4]),1)) 2.3Explanation / Answer
WeightedTotal.java :
_________________
import java.util.ArrayList;
import java.util.Scanner;
public class WeightedTotal {
static int n;
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter number of elements:");
n = sc.nextInt();
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<Double> weights = new ArrayList<Double>();
System.out.println("Enter list of "+n +" numbers:");
for(int i=0;i<n;i++)
nums.add(sc.nextInt());
System.out.println("Enter weights of "+n +" numbers:");
for(int i=0;i<n;i++)
weights.add(sc.nextDouble());
double result = total_numbers(nums,weights);
System.out.printf("%.1f",result);
}
public static double total_numbers(ArrayList<Integer> nums,ArrayList<Double> weights){
double total = 0;
for(int i=0;i<n;i++){
total = total + nums.get(i) * weights.get(i);
}
return total;
}
}
Sample Input and Output:
______________________
Enter number of elements:
3
Enter list of 3 numbers:
1 2 3
Enter weights of 3 numbers:
.1 .5 .4
2.3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.