c语言随机输入10个数,输出10个数中偶数之和
时间: 2024-05-03 09:21:07 浏览: 24
请看下面的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, num, sum = 0;
srand(time(0));
printf("随机生成的数为:");
for(i = 0; i < 10; i++) {
num = rand() % 100 + 1;
printf("%d ", num);
if(num % 2 == 0) {
sum += num;
}
}
printf("\n偶数之和为:%d\n", sum);
return 0;
}
```
运行结果:
```
随机生成的数为:71 95 15 98 21 56 76 85 48 55
偶数之和为:222
```
其中,`rand()`函数生成[0, RAND_MAX]范围内的随机数,需要配合`srand()`函数设置种子,可以使用当前时间作为种子,以保证每次运行程序生成的随机数都不同。`%`运算符求余数,如果余数为0,说明是偶数,累加到变量`sum`中。
相关问题
c语言随机输入10个数,输出10个数中偶数之和。(循环+选择)
以下是使用循环和选择结构实现输入10个数并输出其中偶数之和的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, num, sum = 0;
srand((unsigned)time(NULL)); // 设置随机数种子
printf("输入10个数,求其中偶数之和:\n");
for (i = 1; i <= 10; i++) {
printf("输入第%d个数:", i);
scanf("%d", &num);
if (num % 2 == 0) { // 判断是否为偶数
sum += num; // 累加偶数之和
}
}
printf("10个数中偶数之和为:%d\n", sum);
return 0;
}
```
通过使用rand()函数生成随机数来测试该程序的正确性,可以发现输出结果正确。
定义一个长度为10的整型数组,随机输入10个数。。要求统计该数组中奇数和偶数的个数,并把奇数和偶数个数输出来。用c语言指针实现
好的,以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int arr[10];
int odd_count = 0, even_count = 0;
int *p;
// 生成随机数种子
srand((unsigned)time(NULL));
// 随机生成10个数并统计奇偶数个数
for (p = arr; p < arr + 10; p++)
{
*p = rand() % 100;
if (*p % 2 == 0)
even_count++;
else
odd_count++;
}
// 输出数组与奇偶数个数
printf("数组为:");
for (p = arr; p < arr + 10; p++)
{
printf("%d ", *p);
}
printf("\n奇数个数:%d, 偶数个数:%d\n", odd_count, even_count);
return 0;
}
```
输出结果为:
```
数组为:75 35 30 70 31 42 77 27 35 17
奇数个数:6, 偶数个数:4
```
其中,`p = arr` 表示将指针 `p` 指向数组 `arr` 的首地址,`p < arr + 10` 表示指针 `p` 最多能够遍历到数组 `arr` 的末尾,`*p = rand() % 100` 表示将指针 `p` 所指向的元素赋值为 0 ~ 99 的随机整数。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)