Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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 :)

Risposta accettata

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

Più risposte (1)

Image Analyst
Image Analyst il 19 Ago 2017
Use round():
output = round(output, 2);
  2 Commenti
Hye Sun Choi
Hye Sun Choi il 19 Ago 2017
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 il 19 Ago 2017
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.

Accedi per commentare.

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by