help with proper loop stopping
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I need to make a script that request integer positives or x=0, calculates the average of the given numbers until the user inputs a number x=2*x0 which breaks the loop. if the numbers are not integers or negative it needs to pop a message declaring that. Now I have all of it done but if i input a non integer in my first x it still counts it as the number that breaks the loop and I cannot have that.
my script:
clc,clear;
x=input('enter your number: ');
x1=x;
v=[];
avg=0;
shum=0;
zeros=0;
while x~=2*x1;
if x>=0 & fix(x)==x;
v=[v,x];
end
if x==0
zeros=zeros+1;
end
if fix(x)~=x
fprintf('the number isn''t an integer\n')
end
if x<0
fprintf('your number is negative\n')
end
x=input('enter the next number\n');
end
v=[v,x];
avg=sum(v)/length(v);
fprintf('the avarage of the numbers is:%g\n',avg)
fprintf('the number of zeros is:%d',zeros)
how can i make it so that if my first input is 1.5 for example, it wont be the number to break loop? but the first integer i input for example 2 will i.e(1.5*2=3 wont break loop 2*2=4 will break the loop)
3 comentarios
Stephen23
el 1 de Dic. de 2014
Note that using the variable name zeros is a bad idea, as this is the name of an inbuilt function. Shadowing inbuilt function names like this can cause all sorts of awkward problems later, and is best avoided.
Respuestas (1)
Stephen23
el 1 de Dic. de 2014
A few small changes that can be made to neaten this code, such as:
- using the if conditionals only once each (this makes them much easier to keep track of).
- removing some superfluous variables.
- counting the zeros after the loop.
- preventing evaluation of arbitrary code by using 's' input option for input.
In this version, I used vec to accumulate the values, and cmp to keep track of the (last) two input values to be compared:
vec = [];
cmp = [NaN,NaN];
str = 'Enter a number: ';
while 0~=diff(cmp.*[1,2])
num = str2double(input(str,'s'));
str = 'Enter the next number: ';
if num<0
fprintf('Sorry, that number is negative\n');
elseif fix(num)~=num
fprintf('Sorry, that number isn''t an integer\n');
else
vec = [vec,num]; %#ok<AGROW>
cmp = [num,cmp(1)];
end
end
fprintf('The average of the numbers is: %g\n',mean(vec))
fprintf('The number of zeros is: %d\n',sum(vec==0))
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!