Having trouble with my outputs giving me 4 decimal points when I only want 2?

1 次查看(过去 30 天)
I'm trying to answer the following homework question:
Write a function called fare that computes the bus fare one must pay in a given city based on the distance travelled. Here is how the fare is calculated: the first mile is $2. Each additional mile up to a total trip distance of 10 miles is 25 cents. Each additional mile over 10 miles is 10 cents. Miles are rounded to the nearest integer other than the first mile which must be paid in full once a journey begins. Children 18 or younger and seniors 60 or older get a 20% discount. The inputs to the function are the distance of the journey and the age of the passenger in this order. Return the fare in dollars, e.g., 2.75 would be the result returned for a 4-mile trip with no discount.
And this is my attempt(where d= distance, a=age):
function cost= fare(d, a)
flat_rate= 2;
if (0<=d) && (d<=10) && (18<a) && (a<60)
output= flat_rate + (.25*(round(d)-1))
elseif d>10 && (18<a) && (a<60)
output= flat_rate + (.25*9)+ (.10*(round(d)-10))
elseif (0<=d) && (d<=10) && (18>a || 60<a)
output= (flat_rate + (.25*(round(d)-1)))*(.80)
elseif d>10 && (18>a || 60<a)
output= flat_rate + (.25*9)+ (.10*(round(d)-10))*(.80)
end
I've been trying to test out some values, and the first one I tried was setting d=4, a=44, which should give the expected output of 2.75. However, my output gives me 2.7500. What could I do to fix my outputs to only two decimal points?
Thanks :)

采纳的回答

Chad Greene
Chad Greene 2017-8-19
编辑:Chad Greene 2017-8-19
Type
format bank
And then everything will be printed to two-decimal precision until you restart Matlab. Formatting styles are described here.

更多回答(1 个)

Image Analyst
Image Analyst 2017-8-19
Use round():
output = round(output, 2);
  2 个评论
Hye Sun Choi
Hye Sun Choi 2017-8-19
hey, thanks for your answer. Unfortunately, I still get an output of 2.7500... Not quite sure what I'm doing wrong.
function cost= fare(d, a)
flat_rate= 2;
if (0<=d) && (d<=10) && (18<a) && (a<60)
output= round(flat_rate + (.25*(round(d)-1)),2)
Image Analyst
Image Analyst 2017-8-19
That's just how it's displayed. You can use
fprintf('output = %.2f\n', output);
or use format bank, like Chad said below, it you want to keep the full precision but want to leave off the semicolon and have it echo the value to the command line with only 2 decimal places shown.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by