欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

MODE —— 输入一个数字,求从1加到该数的和(知识点:for循环嵌套while循环)

发布时间:2025/10/17 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 MODE —— 输入一个数字,求从1加到该数的和(知识点:for循环嵌套while循环) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

问题描述:

      终端输入一个数字,求从1加到这个数字的和!

运行结果:

    

代码部分:

#include <stdio.h> int main() {unsigned int sum = 1UL;//Stres the sum of integersunsigned int j = 1U;//Inner loop control variableunsigned int count = 0;//Number of sums to be calculated//Prompt for,and read the input count printf("\nEnter the number of intergers you want to sum: ");scanf(" %u",&count);unsigned int i = 0;//Out loop control variablefor (i = 1;i <= count ;++i){sum = 1UL; //Initialize sum for the inner loopj = 1; //Initalize integer to be addedprintf("\n1");//Calculate sum of integers from 1 to iwhile(j < i){sum += ++j;printf(" + %u",j); //output +j - on the same line }printf(" = %lu",sum); //Output = sum}printf("\n");return 0; }

代码的说明:

        sum变量在外部循环中初始化为1,因为while循环从2开始将值加到sum中,要相加的值存储在j中,它也初始化为1,外部循环的第一个printf()只是输出一个换行符,再输出1,这是要累积的第一个整数,内部循环汇总从2到i的整数。对于j中每个要加到sum上的整数值,内部循环的printf()都会输出+j,它与前面输出的1在同一行上。因此只要j小于i,内部循环就会输出+2,+3等 ,当然外部循环第一次迭代时。i是1,所以不执行内部循环,因为j<i(1<1)是false。


总结

以上是生活随笔为你收集整理的MODE —— 输入一个数字,求从1加到该数的和(知识点:for循环嵌套while循环)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。