Why does my output turn out like this certain times I run my code?
조회 수: 1 (최근 30일)
이전 댓글 표시
Our FSE 100 teacher gave us this prompt:
"Show 'Mutually Prime' or 'Not Mutually Prime' if two numbers are inputted."
So I created this code, which seems to work perfectly fine:
a = input('Input first number: ');
b = input('Input second number: ');
if (a>b)
limit = b
end
if (b>a)
limit = a;
end
counter = 0;
for v = 2:limit
x = mod(a,v);
y = mod(b,v);
if (x == 0) && (y == 0)
counter = 1;
end
end
if (counter == 0 && a~=b)
disp('Mutually Prime');
else
disp('Not Mutually Prime');
end
And most of the time, I'm getting outputs I want, like this one below:
BUT sometimes I'm getting an output that looks like this:
This type of output occassionally shows up, and other times it doesn't, so I'm a little confused, especially since I'm new to MATLAB coding. Is this something MATLAB does, fluctuating the outputs like this? Or is there something wrong in my own code?
Basically, does anyone know if I can fix this so that, somehow, the "limit = ..." portion never shows up in the ouput?
ALSO another problem I'm having is when the two numbers inputted by the user are the same:
It's correct that they aren't mutually prime, but It's printing "100" twice, which I don't want. I can't seem to spot where the problem could be.
Thanks! :)
댓글 수: 0
답변 (1개)
Asad (Mehrzad) Khoddam
2020년 10월 9일
in the first if statement, add a simi-colon ath the end:
if (a>b)
limit = b;
end
Also, you can simplify the first two if statements to:
limit = min(a,b);
참고 항목
카테고리
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!