所以我编写了一个代码,用于读取包含一组数据的文件。之后我将数据四舍五入到小数点后3位。后来,我试图在一些特定范围内取平均数据。范围在0,0.5和0.5到1.0之间......但问题是,当我这样做时,它不会使用舍入数据,而是使用原始数据。我应该如何更改我的代码,以便使用舍入数据?我如何制作代表圆形数据的东西,以便我可以将其用于我的其余编码? 我的代码是
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Data size
#define MAX_ROWS 20
#define MAX_COLUMNS 20
#define LOW_ERROR 0.0
#define HIGH_ERROR 2.5
int main(void)
{
// Decalred variables
int rowIndex = 0;
int columnIndex = 0;
double rawData[MAX_ROWS][MAX_COLUMNS]; // 2-dimensional array to store our raw data
int decimalPlaces = 3;
float rangeValue[6] = { 0.0,0.5,1.0,1.5,2.0,2.5 };
int i, num = 0;
float total = 0.0, average;
// Print out the rawdata array
printf(" --- RAW DATA ---\n");
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
// Read up until the last value
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
{
printf("%.9lf ", rawData[rowIndex][columnIndex]);
}
printf("\n");
}
// Print out the roundup data array
printf(" --- ROUNDED DATA ---\n");
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
// Read up until the last value
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
{
if (rawData[rowIndex][columnIndex] < LOW_ERROR)
printf("%.3f ", LOW_ERROR);
else if (rawData[rowIndex][columnIndex] > HIGH_ERROR)
printf("%.3f ", HIGH_ERROR);
else
printf("%.3f ", ceil(rawData[rowIndex][columnIndex] * 1000.0) / 1000.0);
}
printf("\n");
}
//Calculate and store the averages for each range
printf(" --- RANGE TABLE ---\n");
for (i = 0; i < 5; i++)
{
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
if (rawData[rowIndex][columnIndex] > rangeValue[i] && rawData[rowIndex][columnIndex] <= rangeValue[i + 1])
{
total = total + rawData[rowIndex][columnIndex];
num++;
}
}
average = total / num;
printf("%f \n", average);
total = 0;
average = 0;
num = 0;
}
return 0;
}
答案 0 :(得分:1)
您需要添加一个额外的数组来保存舍入数据。类似的东西:
double roundedData[MAX_ROWS][MAX_COLUMNS];
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
{
roundedData[rowIndex][columnIndex] = ceil(rawData[rowIndex][columnIndex] * 1000.0) / 1000.0);
}
}
在此之后,您可以使用变量roundedData
来计算平均值。