首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言二維陣列傳遞函數:scanf 格式字串 %lf 對應 double

     編輯:程式設計綜合問答

錯誤現象

`input` 函數用 `scanf_s("%d", &arr[i][j])` 讀取 `double` 陣列,導致資料解析錯誤,後續 `sum` 計算結果亂碼。

根因

  • `double` 佔 8 bytes,`%d` 讀取 4 bytes 有號整數,**位元模式完全不同**。
  • `scanf_s` (C11/VC++ 專用) 格式字串與 `scanf` 相同,**`double` 必須用 `%lf`** (`l` = long, `f` = float)。

修正


void input(double arr[][COLS], int n, int m) {
    for (int i=0; i

補充:輸出 `double` 格式

  • `printf("%f", val)` 或 `printf("%.2f", val)` (保留兩位小數)。
  • `display` 函數原碼用 `%d` 輸出 `double` 同樣錯誤,應改 `%f`。

跨平台建議

`scanf_s` 為 Microsoft 延伸,**可移植程式碼請用標準 `scanf`** 並檢查回傳值:


if (scanf("%lf", &arr[i][j]) != 1) { /* 錯誤處理 */ }

總結:double 輸入用 %lf,輸出用 %f;別用 %d。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved