我想编写可以对一组数据进行舍入然后将其打印到3位小数的代码。我知道我需要使用Ceil函数但不知道如何编写正确的代码。我的代码打印的只有1和2!例如,数量为1.2345,最高为2.000。我想使用ceil函数将数字舍入为1.235。
我的代码是:
row = 1;
col = 1;
HIGH_ERROR = 2.5;
LOW_ERROR = 0.0;
% Read the file
rawData = dlmread('data_1.csv',',');
% Get the size
[MAX_ROWS, MAX_COLS] = size(rawData);
errorMap = double(zeros(MAX_ROWS, MAX_COLS));
value = ceil(rawData(row, col)*1000/1000);
%Print the raw data
fprintf('Raw Data\n');
for row = 1 : MAX_ROWS
for col = 1 : MAX_COLS
fprintf('%0.3f ', rawData(row, col));
end
fprintf('\n');
end
%Print the Error Map
fprintf('Error Map\n');
for row = 1 : MAX_ROWS
for col = 1 : MAX_COLS
if rawData(row, col) > HIGH_ERROR
errorMap(row, col) = rawData(row, col);
rawData(row, col) = HIGH_ERROR;
if rawData(row, col) < LOW_ERROR
errorMap(row, col) = rawData(row, col);
rawData(row, col) = LOW_ERROR;
end
end
fprintf('%0.3f ', errorMap(row, col));
end
fprintf('\n');
end
%Print the Rounded Data
fprintf('Rounded Data\n');
for row = 1 : MAX_ROWS
for col = 1 : MAX_COLS
value = ceil(rawData(row, col)*1000/1000);
fprintf('%0.3f ', value);
end
fprintf('\n');
end
答案 0 :(得分:1)
我想你想要
value = ceil(rawData(row, col)*1000)/1000;
答案 1 :(得分:0)
一个很好的技巧应该适用于任何具有round()
的语言:
Round Up(Ceil) - &gt; ceil(x) = round(x + 0.5)
。
Round Down(Floor) - &gt; floor(x) = round(x - 0.5)
。