簡體   English   中英

Matlab循環無法正常工作

[英]Matlab loop not working properly

largest = 0;
num = 0;
temp = 0;
num_flip = 0;

for x = 100 : 999

    for y = x : 999
       num = x*y;
       temp = num2str(num);
       num_flip = str2double(fliplr(temp));

       if num/num_flip == 1
          largest = num;
          one = x;
          two = y;
       end
   end
   end

我試圖找到由兩個3位數字的乘積組成的最大回文,但是由於某種原因,我的循環在x = 924和y = 962處停止,但我知道這沒有答案。 該代碼對於2位數字(10:99)正常工作。

您並沒有在使用該代碼測試最大是否真的是最大。 當您遍歷循環時,有可能在較大的回文中檢測到較小的回文,並且您正在為其分配最大的回文。

嘗試進行此操作,並進行附加測試,以確定新回文是否大於當前最大回文:

largest = 0;
num = 0;
temp = 0;
num_flip = 0;

for x = 100 : 999
    for y = x : 999
       num = x*y;
       temp = num2str(num);
       num_flip = str2double(fliplr(temp));

       if ((num/num_flip) == 1) && (num > largest)
          largest = num;
       end
 end
end

我刪除了這些作業

one = x;
two = y; 

因為不清楚您的問題是什么。 如果出於未顯示的原因需要它們,請重新添加它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM