How to format fprintf with 2 decimals

674 ビュー (過去 30 日間)
JGraf
JGraf 2017 年 2 月 24 日
コメント済み: JGraf 2017 年 2 月 24 日
HI, I have looked at other examples of fprintf, but my formatting on fare(4,75) is off and I am not sure why? fare(4,44) output is correct. Fare (4,75) should be 2.20 (80% of the full fare for 4 miles at 0.80* 2.75) Maybe I have just been looking at this for too long to figure it out.
>> fare(4,44) 2.75 >> fare(4,74) 2.754.00 >>
function price = fare(d, a)
if d <= 1 price2 = 2;
else
price2 = fprintf('%.2f',2 + (min(9, d-1) * 0.25) + (max(0, d-10) * 0.10));
end
if 18 >= a || a >= 60
price2 = fprintf('%.2f',price2*0.80);
end
  2 件のコメント
Adam
Adam 2017 年 2 月 24 日
You haven't said what output you are looking for, you also didn't include the output for fare(4,75) in your question or what is wrong about it.
JGraf
JGraf 2017 年 2 月 24 日
Sorry,
The first one is correct. fare(4,44) = 2.75. The second one is wrong. Ideally it should 80% of the full price, so 2.20

サインインしてコメントする。

採用された回答

Jan
Jan 2017 年 2 月 24 日
編集済み: Jan 2017 年 2 月 24 日
If d > 1 you run this:
price2 = fprintf('%.2f',2 + (min(9, d-1) * 0.25) + (max(0, d-10) * 0.10))
fprintf writes the output to the command window and replies the number of written characters, which is 4: '2.75' .
Do not change the type of the variables during the code. Better perform all calculations with numbers at first and display it once at the end:
function price = fare(d, a)
if d <= 1
price2 = 2;
else
price2 = 2 + (min(9, d-1) * 0.25) + (max(0, d-10) * 0.10);
end
if 18 >= a || a >= 60
price2 = price2 * 0.80;
end
fprintf('%.2f', price2);
end
  1 件のコメント
JGraf
JGraf 2017 年 2 月 24 日
Thank you. That was very helpful!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by