在mysql中计算1-100之间所有奇数的和,请分别用三种循环方式编写程序
时间: 2024-03-24 17:39:55 浏览: 299
以下是在 MySQL 中使用三种循环方式计算 1-100 之间所有奇数的和的程序:
1. WHILE 循环:
```
SET @i = 1;
SET @sum = 0;
WHILE (@i <= 100) DO
IF (@i % 2 = 1) THEN
SET @sum = @sum + @i;
END IF;
SET @i = @i + 1;
END WHILE;
SELECT @sum;
```
2. REPEAT-UNTIL 循环:
```
SET @i = 1;
SET @sum = 0;
REPEAT
IF (@i % 2 = 1) THEN
SET @sum = @sum + @i;
END IF;
SET @i = @i + 1;
UNTIL (@i > 100) END REPEAT;
SELECT @sum;
```
3. FOR 循环:
```
SET @sum = 0;
FOR @i IN 1..100 DO
IF (@i % 2 = 1) THEN
SET @sum = @sum + @i;
END IF;
END FOR;
SELECT @sum;
```
以上三个程序的输出结果都是 2500,即 1-100 之间所有奇数的和。
阅读全文