필터 지우기
필터 지우기

for loop to sum up the integer

조회 수: 7 (최근 30일)
jarvan
jarvan 2014년 11월 1일
답변: Hirusha Perera 2021년 6월 29일
here is the question generate a random integer n in the range from 5 to 9 then loop n times to: -prompt the user for an integer between 1 to 10 -print the sum of the numbers entered so far
here what I got:
n = randi([5,9]);
totalsum = 0;
runsum = 0;
for i = n
int = input('Enter an integer between 1 and 10 :');
runsum = runsum + int;
totalsum = runsum + totalsum;
end
I try to call up the loop, like, Enter an integer between 1 and 10 : 8 but it did not countinous to count up the sum
Can anyone have some suggestion for me?

채택된 답변

MA
MA 2014년 11월 1일
try this:
n = randi([5,9]);
totalsum = 0;
runsum = 0;
for i=1:n
int = input('Enter an integer between 1 and 10 :');
runsum = runsum + int;
totalsum = runsum + totalsum;
end
totalsum
good luck
  댓글 수: 1
jarvan
jarvan 2014년 11월 1일
omg i just forget to input 'totalsum' at last. Thanks so much

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Harry
Harry 2014년 11월 1일
편집: Harry 2014년 11월 1일
You are executing your 'for' loop for only one value, n. Also, I think you probably want to remove your totalsum variable (it doesn't store the total sum... runsum will have the total sum at the end of the loop). Try this:
n = randi([5,9]);
runsum = 0;
for i = 1:n
int = input('Enter an integer between 1 and 10 :');
runsum = runsum + int;
disp([' Sum so far: ', num2str(runsum)]);
end
  댓글 수: 2
jarvan
jarvan 2014년 11월 1일
thanks for your answer
Harry
Harry 2014년 11월 1일
My answer is correct. The answer you accepted was submitted after mine and isn't correct (it doesn't output the correct number).

댓글을 달려면 로그인하십시오.


Hirusha Perera
Hirusha Perera 2021년 6월 29일
Prompt the user for two integersand write a programthat will calculate the summationand the product of all the integers between those inputs inclusively. what is the answer

카테고리

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