[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
题目:求出1~1000之间的所有能被7整除的数,并计算和输出每5个的和
首先我们来看,这道题需要循环所有1-1000之间的数,于是就想到了for循环
for (int value = 1; value <= 1000; value++)
使用for对1~1000的数进行循环,也相同于:
int i = 1; while(i <= 1000) i++;
当然,使用for循环一行就可以解决,我们就使用for循环了;
接着考虑所有能被7整除的数,那必然是这个数与7求余等于0,那么接着嵌套if语句:
if (value % 7 == 0)
看到每五个输出一次和,一开始是想到写一个for语句循环五次之后跳出,但是行不通,于是想到用一个值来统计能被7整除的数出现的次数;
在for之前初始化count(用来计数)和sum(用来统计每五个数的和):
int count = 0; int sum = 0;
继续在if嵌套里面,先对找到的数进行加和,再令计数器加一:
sum += value; Console.WriteLine(value); count++;
现在进行判断,如果计数的值等于5,那么输出加和,并且清空计数器和加和:
if (count == 5) { Console.WriteLine("这5个的和为:" + sum); sum = 0; count = 0; }
那么就可以输出最终结果:
源代码如下:
int count = 0; int sum = 0; for (int value = 1; value <= 1000; value++) { if
(value % 7 == 0) { sum += value; Console.WriteLine(value); count++; if (count
== 5) { Console.WriteLine("这5个的和为:" + sum); sum = 0; count = 0; } } }
将其写到Main方法下面即可
制作不易,求个一键三连~