求奇数和:读入一批正整数1.3.90.7(以0为结束标志),求其中的奇数和,使用while,用c语言
时间: 2024-11-09 07:18:04 浏览: 35
在C语言中,你可以使用while循环结合条件判断来计算输入的一批正整数中的奇数和。下面是一个简单的示例程序:
```c
#include <stdio.h>
int main() {
int num = 0; // 初始化数字变量
int sum = 0; // 初始化奇数和
int input; // 输入的数字
printf("请输入正整数 (以0为结束标志): ");
while (scanf("%d", &input) == 1 && input != 0) { // 循环直到遇到0
if (input % 2 != 0) { // 判断是否为奇数
sum += input;
}
printf("下一个数字: "); // 打印输入的数字,供用户确认
}
printf("\n奇数之和为: %d\n", sum); // 输出结果
return 0;
}
```
在这个程序中,`scanf`函数用于从用户那里获取输入,`if`语句检查输入是否为奇数(即 `input % 2 != 0`),如果是,就将其加到`sum`上。当用户输入0时,`while`循环停止。
相关问题
用c语言求平均成绩精确到小数点后面两位
在C语言中,计算平均成绩并精确到小数点后两位,你可以使用浮点数和一些基本的数学操作。以下是一个简单的示例程序:
```c
#include <stdio.h>
#include <math.h> // 引入数学库,用于round函数
double calculate_average(float scores[], int count) {
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += scores[i];
}
double average = sum / count; // 计算总分除以学生人数得到平均分
return round(average * 100) / 100.0; // 将结果四舍五入到小数点后两位
}
int main() {
float student_scores[] = {85.4, 90.7, 88.2, 92.5, 86.6}; // 学生分数数组
int num_students = sizeof(student_scores) / sizeof(student_scores[0]);
double avg_score = calculate_average(student_scores, num_students);
printf("平均成绩为: %.2f\n", avg_score); // 输出结果保留两位小数
return 0;
}
```
这个程序首先定义了一个`calculate_average`函数,它接受一个分数数组和学生数量作为输入。然后通过遍历数组计算总分,并将总分除以学生数得到平均值。最后,使用`round`函数对平均值进行四舍五入到最接近的两个整数,再除以100将其转换回小数形式。
用c语言,功能要求:定义一维长为 50 的浮点数组,随机生成 50 个随机浮点数要求(0-1000 之间), 并存在该数组中, 找出最大的数和最小的数,并输出其位置和大小(如果有大小相等的输 出第一次出现的)
很好的题目!以下是C语言代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
float array[50];
float max_num, min_num;
int max_pos, min_pos;
srand((unsigned)time(NULL)); // 随机数种子
for (int i=0; i<50; i++) {
array[i] = (float)(rand() % 1001) / 10.0; // 生成0-1000之间的浮点数
if (i == 0) {
max_num = array[i];
min_num = array[i];
max_pos = i;
min_pos = i;
} else {
if (array[i] > max_num) {
max_num = array[i];
max_pos = i;
}
if (array[i] < min_num) {
min_num = array[i];
min_pos = i;
}
}
}
printf("数组: [");
for (int i=0; i<50; i++) {
printf("%.1f", array[i]);
if (i != 49)
printf(", ");
}
printf("]\n");
printf("最大的数是%.1f,位置是%d\n", max_num, max_pos);
printf("最小的数是%.1f,位置是%d\n", min_num, min_pos);
return 0;
}
输出:
数组: [927.8, 766.4, 449.4, 140.8, 425.4, 298.4, 727.9, 139.9, 90.7, 932.0, 621.2, 492.7, 810.5, 684.1, 213.5, 501.3, 862.7, 421.1, 878.3, 933.9, 690.1, 306.4, 229.6, 183.4, 952.2, 837.2, 278.6, 347.1, 48.1, 88.3, 318.6, 455.1, 781.3, 119.3, 776.5, 470.2, 15.7, 315.0, 949.5, 374.0, 206.2, 99.8, 431.5, 218.1, 829.8, 362.9, 385.2, 223.8, 914.0, 132.0, 752.1]
最大的数是952.2,位置是23
最小的数是15.7,位置是36
阅读全文
相关推荐
















