Borrar filtros
Borrar filtros

Summation of numbers using prompts

3 visualizaciones (últimos 30 días)
Mark Coughlin
Mark Coughlin el 26 de Abr. de 2020
Editada: Sindar el 27 de Abr. de 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

Respuesta aceptada

Sindar
Sindar el 27 de Abr. de 2020
Editada: Sindar el 27 de Abr. de 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)?

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by