필터 지우기
필터 지우기

Summarizing numbers using a loop

조회 수: 2 (최근 30일)
Olle Haglund
Olle Haglund 2017년 9월 4일
댓글: Olle Haglund 2017년 9월 5일
Im trying to get the hang of matlab and one exercise i found was to summarize all integers 1-100. It is too easy just using the sum function but my loop won't work.
n=0;
sum=0;
if n<101 %if n is less than 101 (i wan't to include 100) - do the following:
n=n+1; %add 1 to n
sum=sum+n; %add n to sum
end
sum %display sum
end
I get sum=1, why?

답변 (1개)

Geoff Hayes
Geoff Hayes 2017년 9월 4일
편집: Geoff Hayes 2017년 9월 4일
Olle - your code seems to be missing the for loop so I suspect that is the reason that you are only getting a value of 1. Consider the following
mySum = 0;
for k = 1:100
mySum = mySum + k;
end
We iterate over each integer from 1 to 100 and add that value to our running total (the mySum variable). (You were using a variable named sum to do the same thing. I recommend against this since sum is a built-in MATLAB function and "replacing" the function with your local variable will cause unexpected errors if you then choose to use the sum function.)
See loop control statements for examples on how to repeat blocks of code.
  댓글 수: 1
Olle Haglund
Olle Haglund 2017년 9월 5일
Thanks man! I actually found a solution using a while loop instead. But it's good to know more than one way.

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

카테고리

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