DEV Community

codemee
codemee

Posted on

3 3

在 Windows 平台使用 e 格式代碼時讓指數顯示 2 位

根據 C99 的規格書, 使用格式化輸出入時格式代碼 e/E 的指數部分至少是 2 位數, 而且只有必要時才會增加位數, 也就是說, 預設就是 2 位數, 例如:

#include <stdio.h>
#include <math.h>

int main(){
  printf("%010.4E\n", 1.13145);

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

結果如下:

1.1315E+00

Enter fullscreen mode Exit fullscreen mode

但是在 Windows 平台上, 你會發現指數至少會有 3 位數, 同樣的程式執行結果會不同:

1.1315E+000

Enter fullscreen mode Exit fullscreen mode

如果你的程式需要跨平台, 可以在格式化輸出前使用 _set_output_format 函式設定指數的位數, 例如:

#include <stdio.h>
#include <math.h>

int main(){
  _set_output_format(_TWO_DIGIT_EXPONENT);
  printf("%010.4E\n", 1.13145);

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

其中參數 _TWO_DIGIT_EXPONENT 表示要和規格書一樣使用 2 位數, 如果傳入 0, 就恢復為 3 位數。

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up