gpt4 book ai didi

c - 编写一个访问数组的主程序

转载 作者:行者123 更新时间:2023-11-30 21:22:57 25 4
gpt4 key购买 nike

我需要家庭作业帮助!这不是一项到期的作业,所以请不要评论说我需要自己解决这个问题。只是做一些额外的练习来准备考试。

我需要编写一个主程序,计算数字 6.0 在一个大型 double 组中出现的次数,然后打印出数组中的元素数量以及 6.0 的值的数量。另外,计算并打印数组中所有元素的平均值,精确到小数点后 7 位。

使用 for 循环。

数组 fArray[] 在名为 arraypractice.h 的文件中定义。将其添加到您的项目目录并在代码中引用它,如下所示:

int main(void)
{
#include "arraypractice.h“
.

我只确定了数组的长度,但我不知道从这里开始:

int main(void)
{
#include "arraypractice.h"

int n;
n = sizeof(fArray);
int size;

printf("Size of the given array is %d\n", n / sizeof(double));

最佳答案

您需要在教程中查找 for 循环等:p

您关于小数点后 7 位平均值的问题属于精度主题。我使用的是%12.7ff用于 double ,12.7表示小数点前12位,小数点后7位。

#include <stdio.h>

int main(void) {
double fArray[10] = {1.2, 12.6, 6.0, 5.3, 3.2, 6.0, 5.0, 60.3, 6.0, 1.1};
int count = 0;
int sixes = 0;
double sum = 0;

for (int i = 0; i < (sizeof(fArray) / sizeof((fArray)[0])); i++)
{
count +=1;
sum += fArray[i];
if(fArray[i] == 6.0){
sixes ++;
}
}
printf("Total elements: %d \n Sixes found: %d \n Average is: %12.7f", count, sixes, sum/count);
return 0;
}

编辑

上面的代码可以正常运行,但是对于从文件中读取 double 。您必须详细说明您的文件是什么样子,否则可能需要在 Stack Overflow 上再提出一个 问题 搜索

...但是这个(未经测试的)代码示例应该可以帮助您入门:)

FILE *f=fopen("file.txt","r");

if(f==NULL)
return 1;

double values[10];
unsigned int i;

for(i = 0; i < 10; ++i) {
fscanf(f, "%lf",&values[i]);
printf("%lf\n",values[i]);
}
close(f);

关于c - 编写一个访问数组的主程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com