【问题标题】:procedure to find numbers divisible by 3 and by 2 between 1-100在 1-100 之间找到可被 3 和 2 整除的数字的过程
【发布时间】:2016-11-29 13:44:04
【问题描述】:

我有任务,让程序确定可被 3 和 2 整除的数字,但我只能尝试被 3 和 2 整除,就像这样

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `divisible`()
BEGIN
  declare str VARCHAR(255) default '';
  declare x INT ;



  SET x = 1;
  set str = '';

while x <= 100 do

    if (x mod 3=0 &&  x mod 2 =0)  then 
        set str= CONCAT(str, x ,',')  ;  

    end if;
    set x=x+1;

end while;

SELECT str ;
END

上述程序的输出:'6,12,18,24,30,36,42,48,54,60,66,72,78,84,90,96,'

如何产生不同的输出,因此可以被 3 整除:3,6,9,12 ... 和 2:1-100 之间的 2,4,6,8。

【问题讨论】:

  • 问题是什么?程序看起来还可以。请阅读How-to-Ask 这里是START 了解如何提高问题质量并获得更好答案的好地方。
  • 你可以通过简单的查询为什么需要程序来做到这一点
  • @jaidutt 我没有看到一个简单的查询。也许您可以将其显示为答案
  • @jaidutt 我的任务,所以我必须遵守规则
  • 哇!最糟糕的 SQL 用法。曾经!! :-)

标签: mysql loops stored-procedures


【解决方案1】:

首先,您可以得到既能被 2 也能被 3 整除的数字列表,只需意识到这是 6 的所有倍数:

set m = 6;
set x = m;
set str = '';
while x <= 100 do
    set str = CONCAT(str, x ,',');
    set x = x + m;
end while;

当然,您可以使用相同的方法来获得任何倍数的列表,只需将乘数 m 更改为其他值即可。


如果您想要被二三(而不是二三)整除的数字,您只需将原始代码更改为使用or而不是and:

if (x mod 3 = 0 || x mod 2 = 0)  then

【讨论】:

    【解决方案2】:
    SET x = 1;
    set str2 = '2: ';
    set str3 = '3: ';
    set str23 = '2|3: ';
    
    while x <= 100 do
    
        if (x mod 2 = 0)  then 
            set str2 = CONCAT(str, x ,',')  ;      
        end if;
    
        if (x mod 3 = 0)  then 
            set str3 = CONCAT(str, x ,',')  ;      
        end if;
    
        if (x mod 2 = 0 &&  x mod 3 = 0)  then 
            set str23= CONCAT(str, x ,',')  ;      
        end if;
        set x=x+1;
    
    end while;
    
    SELECT str2
    UNION
    SELECT str3
    UNION
    SELECT str23
    ;
    END
    

    【讨论】:

    • 你的程序只能读取str2。那是我的问题,是sql程序只能显示一个输出吗?或者我们必须尝试使用​​ concat? SELECT concat("result_1: ", str2, "result_2: ", str3,"result_3",str23 ) AS "divisible";但结果不同:\
    猜你喜欢
    • 2022-01-23
    • 2019-04-16
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2012-09-23
    相关资源
    最近更新 更多