Write a program that calculates sum of the integers numbers
5 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(5 个)
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
0 个评论
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 个评论
Paulo Silva
2011-4-11
I hate when it takes more time to understand what people want than to make their answer!
Paulo Silva
2011-4-11
v=2:30;
sum(v(~mod(v,2)))
3 个评论
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
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
2011-4-11
or
sum(2:2:30)
2 个评论
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
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
2011-4-11
disp(240)
Or, for pedants who claim that evaluation is not the same as calculation,
disp(239+1)
1 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!