Effacer les filtres
Effacer les filtres

Summation of numbers using prompts

3 vues (au cours des 30 derniers jours)
Mark Coughlin
Mark Coughlin le 26 Avr 2020
Modifié(e) : Sindar le 27 Avr 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

Réponse acceptée

Sindar
Sindar le 27 Avr 2020
Modifié(e) : Sindar le 27 Avr 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)?

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by