MODE —— 输入一个数字,求从1加到该数的和(知识点:for循环嵌套while循环)
生活随笔
收集整理的這篇文章主要介紹了
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循环)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MODE —— 输出一个高度和宽度固定的
- 下一篇: MODE —— 计算10个分数的平均值(