Summation of numbers using prompts

4 Ansichten (letzte 30 Tage)
Mark Coughlin
Mark Coughlin am 26 Apr. 2020
Bearbeitet: Sindar am 27 Apr. 2020
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

Akzeptierte Antwort

Sindar
Sindar am 27 Apr. 2020
Bearbeitet: Sindar am 27 Apr. 2020
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)?

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by