Summation of numbers using prompts

3 次查看(过去 30 天)
I want the program to prompt the user for the value n (the number of values to be added together). I then want the program to prompt the user n times for a number, for it to the add these numbers together and finally print the result. Any help would be appreciated, thank you! This is my code so far:
function sumnnums(n);
prompt='Enter the value of n: ';
n=input(prompt);
sum=0;
for i=1:n
prompt='Enter a number: ';
x(i)=input(prompt);
end
sum=sum+x;
formatSpec='The sum of the numbers is %6.4f\n';
fprintf(formatSpec,x(i));
end

采纳的回答

Sindar
Sindar 2020-4-27
编辑:Sindar 2020-4-27
Two errors:
  • The function should not have n as an argument. Wait to ask the user
  • don't use "sum" as a variable name; it's a function
  • if you want to do "sum=sum+x" it needs to be in the loop and x needs to be a scalar. But, there's no reason to do it like that since you're already storing the results in an array. Just do this:
mysum = sum(x);
  • if you've calculated the sum, why are you printing x(i)?

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by