How to display all decimal numbers for floating numbers?

53 ビュー (過去 30 日間)
Anne Nguyen
Anne Nguyen 2019 年 9 月 15 日
コメント済み: dpb 2019 年 9 月 15 日
The task I have to perform is take 2 user input numbers that must be floating numbers and add them together. However, when I do this, it cuts off at 4 decimal places. How do I make it so that it displays all decimal numbers? Do I have to use something with %f? I cannot use the "format" command. I am relatively new to MATLab, so any help would be appreciated! Below is what I have so far.

採用された回答

Bruno Luong
Bruno Luong 2019 年 9 月 15 日
Try this
fprintf('num1+num2 = %1.16g\n',adding_num1_and_num2)
  2 件のコメント
Anne Nguyen
Anne Nguyen 2019 年 9 月 15 日
Instead of %1.16g", am I allowed to use %f? I am also not allowed to use "g".
Walter Roberson
Walter Roberson 2019 年 9 月 15 日
%f will display 6 digits by default. 6 digits is infinitely short of "all" of the decimal digits.

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2019 年 9 月 15 日
There are an infinite number of decimal 0's at the end of any floating point number, so it is not possible to make it display all of the decimal numbers.
It looks to me as if you are running MS Windows. The MS Windows internal libraries cannot correctly convert floating point numbers to show all stored decimals like Mac can (and newer versions of Linux can, I hear.)
You will need to use a routine such as num2strexact https://www.mathworks.com/matlabcentral/fileexchange/22239-num2strexact-exact-version-of-num2str to get all of the representable digits.

dpb
dpb 2019 年 9 月 15 日
I'll guess for homework Q? the answer is less esoteric than Walter's take... :)
Yes, if you need more precision than the default display format and the instructor says using the format command to change display mode is not permitted for the assignment, then your supposition of using a formatting string is correct. One supposes the class has recently touched on that topic.
Without giving away the store on writing answer directly, look at one of the following options --
num2str() with an optional formatting string, or
fprintf() using the default 1 for the file ID to echo to the command line (presuming that's where you want the answer to be displayed). A default double has roughly 15 decimal digits of precision; you may have been instructed how many digits to display? Those should give hints on writing/displaying more significant digits...
  2 件のコメント
Anne Nguyen
Anne Nguyen 2019 年 9 月 15 日
With fprintf, am I supposed to add %f at the end of the statement?
dpb
dpb 2019 年 9 月 15 日
Read the doc...the argument list is fileID, fmtString, outputlist

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by