找到整数和的和的概念是这样找到的,首先,我们将找到从1到n的数字的和,然后将所有的和相加,得到一个值,这个值就是我们所需的和的和。
对于这个问题,我们给出了一个数字n,我们要找到和的和,让我们举个例子来找到这个和。
n = 4
登录后复制
Now we will find the sum of numbers for every number from 1 to 4 :
Sum of numbers till 1 = 1Sum of numbers till 2 = 1 + 2 = 3Sum of numbers till 3 = 1 + 2 + 3 = 6Sum of numbers till 4 = 1 + 2 + 3 + 4 = 10Now we will find the sum of sum of numbers til n :Sum = 1+3+6+10 = 20
登录后复制
对于找到n个自然数的和的和,我们有两种方法:
方法1 – 使用for循环(低效)
方法2 – 使用数学公式(高效)
方法1 – 使用for循环
在这种方法中,我们将使用两个for循环来找到和的和。内部循环找到自然数的和,外部循环将此和添加到sum2并将数字增加一。
示例
#include int main() { int n = 4; int sum=0, s=0; for(int i = 1; i输出
The sum of sum of natural number till 4 is 5登录后复制
方法2-使用数学公式
我们有一个数学公式用于求解n个自然数的和。数学公式方法是一种高效的方法。
求解n个自然数的和的数学公式为:
sum = n*(n+1)*(n+2)/2登录后复制
Example
的中文翻译为:
示例
#include int main() { int n = 4; int sum = (n*(n+1)*(n+2))/2; printf("the sum of sum of natural number till %d is %d", n,sum); return 0;}登录后复制
输出
the sum of sum of natural number till 4 is 60登录后复制
以上就是C程序中的前n个自然数之和的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2585264.html