回覆列表
  • 1 # 使用者8209154827005

    你問的這個問題很有意思啊,matlab要保留任意位數,是一個比較值得研究的東西。

    預設format也就是format short是保留4位小數,format long 是保留14位,如果要保留兩位或者六位,就存在如何設定的問題。本人做了點總結,給出以下方法

    方法1:digits+vpa

    format long

    a = input("please give a number which will be changed:");

    n = input("how many decimal digits will you keep: ");

    num = floor(a);

    str = num2str(num);

    len = length(str);

    err = a-num;

    digits(n+len); % 此處為需要的小數位+整數位數

    need_num = num+vpa(err,n+len); %%%% 這裡得到的是符號型

    need_str = num2str(double(need_num)) %%%%% 再次轉換獲得字元型

    方法2:round 函式法

    format long

    a = input("please give a number which will be changed:");

    n = input("how many decimal digits will you keep: ");

    b = a*10^n;

    aa = round(b);

    need_num = aa/10^n; %%%%% 先化成整數,再轉成小數

    need_str = num2str(need_num)

    方法3:直接轉成字串再擷取

    format long

    a = input("please give a number which will be changed:");

    n = input("how many decimal digits will you keep: ");

    num = floor(a);

    str = num2str(num);

    len = length(str);

    str1 = num2str(a);

    need_str = str1(1:(len+n+1)) %%%取需要的長度,這裡需要加上整數長和小數點1位

    方法4:fprintf方法

    a = input("please give a number which will be changed:");

    %n = input("how many decimal digits will you keep: ");

    fprintf("a = %3.2f",a) %%%%3.2f中.2就是小數位數

  • 中秋節和大豐收的關聯?
  • 籃球投籃技巧?