hhjc.net
当前位置:首页 >> C语言求1到n的奇数和 >>

C语言求1到n的奇数和

你好!int i,evenNumberSum=0,unevenNumberSum=0,n; scanf("%d",&n); for(i=1;i{ if(i%2==0)unevenNumberSum+=i; else evenNumberSum+=i; } 如有疑问,请追问.

#include<stdio.h> int main() { int oddsum(int num); int n; printf("请输入一个正整数:\n"); scanf("%d",&n); printf("1到%d之间的所有奇数之和:%d\n",n,oddsum(n)); return 0; } int oddsum(int num) { if(num%2==0) return (1+num-1)*(num/2)/2; else return (1+num)*((num+1)/2)/2; }

#include <stdio.h>int main(){int n,i;double sum;scanf("%d",&n);for(i=1,sum=0;i<=n;i+=2)sum+=1.0/i;printf("%lf",sum);return 0;}

#include<stdio.h>void main(){int n,i=1,j=2,sum1=0,sum2=0;scanf("%d",&n);do{sum1=sum1+i;i++;i++;}while(i<=n);do { sum2=sum2+j;j++;j++;}while(j<=n);printf("sum1=%d,sum2=%d",sum1,sum2);}

#include int main(){ long sum1=0,sum2=0; int n,i; printf("请输入n: "); scanf("%d",&n); for(i=1;i 评论0 0 0

连续和=(首项+末项)*项数÷2,计算中关键要注意项数 若n为偶数,则奇数和=(1+n-1)*(n/2)/2=(n^2)/4 表示4分之n方 偶数和=(2+n)*(n/2)/2=(n^2)/4 +n/2 若n为奇数,则奇数和=(1+n)*((n+1)/2)/2=((n+1)^2)/4 表示4分之(n+1)方 偶数和=(2+n-1)*((n-1)/2)/2=((n+1)^2)/4 +(n-1)/2

最基础的思路,是逐个求阶乘,并累加.不过由于阶乘是从1乘到n,所以每个数都单独求一次阶乘,会有很多重复运算,影响效率.所以更快捷的方式是,在上一个数的阶乘基础上,直接乘上本身,得到当前数的阶乘.以此为主导,代码如下:#include <stdio.h> int main() { int n, i, n1 = 1,s=0; scanf("%d",&n);//输入n值. for(i=1; i <= n; i ++) { n1*=i;//计算i的阶乘. s+=n1;//累加. } printf("%d\n", s);//输出结果.}

# include <stdio.h> void main() { int i, n, sum1 = 0, sum2 = 0; printf("请输入一个正整数:"); scanf("%d", &n); for(i = 1; i <= n; i++) { if(i % 2 == 1) sum1 += i; else sum2 += i; } printf("1到%d之间的奇数和为:%d\n", n, sum1); printf("1到%d之间的偶数和为:%d\n", n, sum2); } 望采纳

int main(){int i=1;double res1=0;int res2=0,res3=0;while(i++ 评论0 0 0

#include<stdio.h> int main(){ int sum = 0; int n,i; scanf("%d",&n); for(i=0;i<=n;i++){ if(i%2==1){ sum+=i; } } print("%d",sum); }

网站首页 | 网站地图
All rights reserved Powered by www.hhjc.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com