Write a program that calculates sum of the integers numbers

조회 수: 1 (최근 30일)
Aaron Moris
Aaron Moris 2011년 4월 11일
댓글: DGM 2023년 3월 4일
What is the product if the question is write a program that calculates and prints the sum of the even integers from 2 to 30?

답변 (5개)

Florin Neacsu
Florin Neacsu 2011년 4월 11일
2+4+6+...+30=2(1+2+3+...+15)=2*(15*16)/2=15*16
So 2+4+...+n = floor(n/2)*(floor(n/2)+1).
Regards, Florin

Matt Fig
Matt Fig 2011년 4월 11일
The product would be the sum of the even integers from 2 to 30 ;-).
Seriously, what have you tried so far on this homework problem?
  댓글 수: 2
Sean de Wolski
Sean de Wolski 2011년 4월 11일
You might need some bubble wrap for that.
Paulo Silva
Paulo Silva 2011년 4월 11일
I hate when it takes more time to understand what people want than to make their answer!

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


Paulo Silva
Paulo Silva 2011년 4월 11일
v=2:30;
sum(v(~mod(v,2)))
  댓글 수: 3
Image Analyst
Image Analyst 2017년 8월 15일
mod(v, 2) will be either 0 or 1. The tilde inverts that, so 0 becomes 1, and 1 becomes 0.
DGM
DGM 2023년 3월 4일
Importantly, using ~ implicitly casts the numeric result from mod() to logical (along with doing the inversion). Otherwise, the indexing operation would fail if the indices were numeric 0 and 1, as you'd be trying to access the zeroth element of v.

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


Doug Eastman
Doug Eastman 2011년 4월 11일
  댓글 수: 2
Paulo Silva
Paulo Silva 2011년 4월 11일
that's simple but if you change the start value from 2 to 1 you do the sum of odd numbers instead, also if the last value is 31 or some odd number the result won't be correct, unfortunately that's not very flexible code.
Paulo Silva
Paulo Silva 2011년 4월 11일
btw that does work and is a good answer for the question (only if the values don't change), +1 vote

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


Matt Tearle
Matt Tearle 2011년 4월 11일
disp(240)
Or, for pedants who claim that evaluation is not the same as calculation,
disp(239+1)
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2011년 4월 11일
This is definitely the most compact and efficient way to do this. +1.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by