【发布时间】:2017-09-03 06:12:25
【问题描述】:
所以我编写了一个代码,它读取包含一组数据的文件。之后,我将数据四舍五入到小数点后 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;
}
【问题讨论】:
-
我可以看到您在哪里有代码来 printf() 输出舍入值,但看不到您实际舍入数组中的值的位置?此外,您的缩进需要注意 - 我无法清楚地看到 main() 开始/结束的位置。