所以我想寫一個代碼,它可以讓我將任意數字舍入到小數點後3位。我對圍捕一個數字代碼是這樣的:C中的舍入函數
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
{
printf("%.3f ", ceil(rawData[rowIndex][columnIndex] * 1000.0)/1000.0);
}
}
但昨天我的老師告訴我們要使用具有這樣的結構的代碼:
float roundValue(float value, int decimalPlaces)
{
// Place rounding code here
return value;
}
我不太清楚怎麼寫這種格式的代碼!我是編碼方面的初學者,所以這可能非常愚蠢。
更新: 所以我只是閱讀下面的所有意見,並試圖編寫代碼,但仍有問題。我的代碼是:
double roundValue(double value, int decimalPlaces)
{
value = roundf(value * pow(10, decimalPlaces))/pow(10, decimalPlaces);
return value;
}
int main(void)
{
int rowIndex = 0;
int columnIndex = 0;
double rawData[MAX_ROWS][MAX_COLUMNS]; // 2-dimensional array to store our
raw data
double value = rawData[MAX_ROWS][MAX_COLUMNS];
int decimalPlaces = 3;
// Print out the roundup data array
printf(" --- ROUNDED DATA ---\n");
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
{
printf("%.3f ", roundValue(value, 3));
}
printf("\n");
}
return 0;
}
它給我所有的數字只有0。
你需要澄清你的問題,並描述你已經嘗試過的步驟... – PureW
那麼,問你的老師?當你在這個時候,告訴他使用'float'是一個**可怕的**想法,因爲它的精度有限...... –
如果你理解浮點二進制表示,你不會「*認爲*」爲3小數位。如果*真的*需要3位小數,請嘗試使用固定點格式。 –