TA的每日心情 | 开心 2014-6-18 08:29 |
---|
签到天数: 14 天 [LV.3]偶尔看看II
滴水大师
 
- 积分
- 2345
|
题目
解决代码及点评这道题练习数组的遍历
- <pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"></pre><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code">/************************************************************************/
- /*
- 1.有一个正整数数组,包含N个元素,要求编程求出其中的素数之和以及所有素数的平均值。
- */
- /************************************************************************/
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- bool IsSuShu(int num)
- { if (num<2)
- return false;
- for (int i=2;i<=sqrt((double)num);i++)
- {
- if (num%i==0)
- {
- return false;
- }
- }
- return true;
- }
- void main()
- { int num=0;
- int sum=0;
- const int N=10;
- int arr[N]={0};
- for (int i=0;i<N;i++)
- {
- arr=rand()%10; // 获取随机数
- printf("%3d",arr);
- if (IsSuShu(arr)) // 判断是否素数,如果是,则累加,并计数
- {
- num++; // 计数
- sum+=arr; // 累加
- }
- }
-
- printf("共有素数%d个 和为%d 平均数为%f",num,sum,sum/(num*1.0)); // 输出结果
- system("pause");
- }</pre><br><br><br><br></pre>
|
|