C 语言实例 - 计算自然数的和

C 语言教程 · 2019-02-20 18:14:31

自然数是指表示物体个数的数,即由0开始,0,1,2,3,4,……一个接一个,组成一个无穷的集体,即指非负整数。

实例 - 使用 for

#include <stdio.h> int main() { int n, i, sum = 0; printf("输入一个正整数: "); scanf("%d",&n); for(i=1; i <= n; ++i) { sum += i; // sum = sum+i; } printf("Sum = %d",sum); return 0; }

实例 - 使用 while

#include <stdio.h> int main() { int n, i, sum = 0; printf("输入一个正整数: "); scanf("%d",&n); i = 1; while ( i <=n ) { sum += i; ++i; } printf("Sum = %d",sum); return 0; }

运行结果:

输入一个正整数: 100
Sum = 5050

实例 - 使用递归

#include <stdio.h> int addNumbers(int n); int main() { int num; printf("输入一个整数: "); scanf("%d", &num); printf("Sum = %d",addNumbers(num)); return 0; } int addNumbers(int n) { if(n != 0) return n + addNumbers(n-1); else return n; }

点击查看所有 C 语言教程 文章: https://codercto.com/courses/l/17.html

查看所有标签

Handbook of Data Structures and Applications

Handbook of Data Structures and Applications

Dinesh P. Mehta / Chapman and Hall/CRC / 2004-10-28 / USD 135.95

In the late sixties, Donald Knuth, winner of the 1974Turing Award, published his landmark book The Art of Computer Programming: Fundamental Algorithms. This book brought to- gether a body of kno......一起来看看 《Handbook of Data Structures and Applications》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具