count function, whwn i enter numbers and its wrong the count isnt going read the commnets i made

2 次查看(过去 30 天)
choice= input('Enter a vector sufficent for an odd-order polynomial: '); % inputs an even or odd vector [1]- odd [1 2]-even
a=length(choice);
Count = 1;
%b = mod(a,2);
while Count < 5 && mod(a,2)==0
choice= input('Enter a vector sufficent for an odd-order polynomial: ');
Count = Count+1; % this part isnt working for some reason
if Count > 5
warning('Odd number of coefficients entered. Last element removed');
choice(:,end)=[];
end
end
if mod(a,2)~=0
fprintf('Please enter a valid vector.\n');
end

回答(1 个)

Walter Roberson
Walter Roberson 2020-2-25
编辑:Walter Roberson 2020-2-25
Suppose Count has reached 3 and mod(a, 2)==0. The loop will continue. choice will be input. Count will be incremented to 4. 4 is not greater than 5 so the last element of choice is not removed.
We return to the loop test. Count is 4 and that is less than 5. a has not changed so mod(a, 2) is still 0. So you will prompt for choice again, and then you will increment Count from 4 to 5. 5 is not greater than 5 so the last element of choice is not removed. Notice that the content of choice from the last iteration was ignored.
We return to the loop test. Count is 5 which is not < 5 so the loop terminates.
If you think about this, the test Count>5 can not be satisfied, so there is no point in having that code.
What went wrong? This:
You failed to update "a" after you changed the content of choice
  2 个评论
Walter Roberson
Walter Roberson 2020-2-25
My last paragraph already highlights what needs to be changed.
You initialize a when you read in choice the first time. After that you never change a. That is the mistake. You need to change a every time you change choice.

请先登录,再进行评论。

类别

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