What's wrong with my code? (Beginner's question; geometric sum)
显示 更早的评论
This is the sum I'm trying to use:
1 + r^2 + r^4 + r^6 + ... + r^n
If n isn't even, I'm supposed to display an error.
Here's my code:
function [sum] = series(r,n)
sum = 1;
if mod(n,2) == 0
for i=2:n
sum = sum + r.^i;
end
else
disp('Error!');
end
end
Keeps returning the wrong value. What's wrong with my code?
采纳的回答
更多回答(1 个)
Image Analyst
2014-11-13
Don't use sum as the name of a variable since it's a built-in function. You want
for k = 2 : 2 : n
theSum = theSum + r^k;
类别
在 帮助中心 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!