Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情。
前言
Hello everyone, I'm Zeyu, and today we will start the seventh question of our C language topic. Don't know what your previous topics will be? It doesn't matter if you don't. If you can, it means you are very good (if you are just learning), well, let's not talk nonsense and start our topic 7.
题目描述
分别用while语局和for语句循环求和(从1~100数字)
题目分析
这道题目主要其实就是一个循环的使用,那么在这里我们就不得不介绍下循环的关键字了!
for和while,这两个关键字就是求解本题目的关键。但是在程序的使用当中for循环是比while循环灵活的。而是在1~100之间就可以带入循环,再创建一个总变量进行存储值。
那么以上就是对这道题目的分析了,不知道你脑海中有没有思路呢?
题目代码
代码示例如下👇
for语句代码
#include <stdio.h>
int main(void)
{
int i;
int sum = 0;
for (i = 0; i <= 100; i++)
{
sum = i + sum;
}
printf("sum = %d\n", sum);
return 0;
}
while语句代码
#include <stdio.h>
int main(void)
{
int i = 0;
int sum = 0;
while (i <= 100)
{
sum += i;
i++;
}
printf("sum = %d\n", sum);
return 0;
}
运行结果
编译运行结果:sum = 5050
两次都是!
最后
不知道你学会了没有是不是很容易距离接下来还有93题加油!