write a function to round off numbers

조회 수: 5 (최근 30일)
Zcarfaz
Zcarfaz 2014년 2월 28일
댓글: Image Analyst 2014년 2월 28일
Write your own roundn function that takes a floating point value as its input and rounds its nth decimal digit to the nearest number.
>> res = roundn(5.672,3); % results in res = 5.67
>> res = roundn(5.677,3); % results in res = 5.68
>> res = roundn(-5.672,3); % results in res = -5.67
>> res = roundn(-5.677,3); % results in res = -5.68

답변 (2개)

Image Analyst
Image Analyst 2014년 2월 28일
Try multiplying by a factor of 10 then rounding and dividing. That should be a good hint - probably too much of one.
  댓글 수: 2
Zcarfaz
Zcarfaz 2014년 2월 28일
ok I got this for but when i run the function it won't give the right answer but when I do it manually on the command window it works. also this is not the way i have to do it I need to write a for loop to check the value of the myfloat and then change the factor of 10 accordingly. please help. thanks!
function output = roundn(myinput,myfloat)
if myfloat == 1
output = round(myinput*10)/10;
fprintf('%.1f\n', output);
end
if myfloat == 2
output = round(myinput*100)/100;
fprintf('%.2f\n', output);
end
if myfloat == 3
output = round(myinput*1000)/1000;
fprintf('%.3f\n', output);
end
end
Image Analyst
Image Analyst 2014년 2월 28일
Instead of checking for every possible factor of 10, why don't you just use 10^myFloat?
And how are you running it, if not from the command line? What value are you passing in when it does not run?

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2014년 2월 28일
This cannot be done in MATLAB, not if the values are to be stored numerically as datatype single() or double().
>> fprintf('%.999g\n', 0.1)
0.1000000000000000055511151231257827021181583404541015625
This establishes that even if you had 0.1 already given, that you do not actually get exactly 0.1 stored.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by