“求数字之和的三种算法”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (建立内容为“https://www.bilibili.com/video/BV1Ra4y1p7Si”的新页面) |
Jihongchang(讨论 | 贡献) |
||
第1行: | 第1行: | ||
https://www.bilibili.com/video/BV1Ra4y1p7Si | https://www.bilibili.com/video/BV1Ra4y1p7Si | ||
+ | |||
+ | === 题目 === | ||
+ | 例如:1234→1+2+3+4=10 | ||
+ | |||
+ | === 第一种 === | ||
+ | while 循环<syntaxhighlight lang="cpp"> | ||
+ | #include<stdio.h> | ||
+ | |||
+ | int f(int n) | ||
+ | { | ||
+ | int ret = 0; | ||
+ | while (n > 0) | ||
+ | { | ||
+ | ret = ret + (n % 10); | ||
+ | n = n / 10; | ||
+ | } | ||
+ | return ret; | ||
+ | } | ||
+ | |||
+ | int main() { | ||
+ | int a = 1234; | ||
+ | int ret = f(a); | ||
+ | printf("ret = %d \n", ret); | ||
+ | return 0; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | === 第二种 === | ||
+ | 递归 |
2022年11月9日 (三) 06:42的版本
https://www.bilibili.com/video/BV1Ra4y1p7Si
题目
例如:1234→1+2+3+4=10
第一种
while 循环
#include<stdio.h>
int f(int n)
{
int ret = 0;
while (n > 0)
{
ret = ret + (n % 10);
n = n / 10;
}
return ret;
}
int main() {
int a = 1234;
int ret = f(a);
printf("ret = %d \n", ret);
return 0;
}
第二种
递归