Why does my output turn out like this certain times I run my code?

조회 수: 1(최근 30일)
Kinza Rashid
Kinza Rashid 2020년 10월 9일
댓글: Kinza Rashid 2020년 10월 9일
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! :)

답변(1개)

Asad (Mehrzad)  Khoddam
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);
  댓글 수: 1
Kinza Rashid
Kinza Rashid 2020년 10월 9일
Thank you so much! That corrected the "limit = ..." problem, but is there a way to stop a duplicate being printed of the second variable if the two inputs are the same value (shown in the last picture)?

댓글을 달려면 로그인하십시오.

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by