簡體   English   中英

輸入數組加倍的麻煩

[英]Trouble with entering doubles into an array

我正在處理一個交流程序,當系統提示輸入雙精度時,該程序不會繼續進行。 它會跳過,並且不允許我在循環的第一次運行后輸入另一個數字。 這是代碼示例:

void total_max(double sale[], int n, double *total, double *max, int *max_id);

int main()
{
  int n = 7; // length of an array
  double sale[n];
  int i;
  for(i=0; i < n; i++)
  {
    printf("Enter the sales for salesperson %d\n", i+1);
    scanf("%.2f", &sale[i]);
    printf("\n");
  }

我做錯什么了嗎?

fgets可用於讀取輸入行,然后使用strtod解析該行。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n = 7; // length of an array
    double sale[n];
    char input[50] = "";
    char *next = NULL;
    int i;
    for(i=0; i < n; i++)
    {
        do {
            printf("Enter the sales for salesperson %d\n", i+1);
            if ( fgets ( input, sizeof input, stdin)) {//read up to 49 characters or up to newline
                sale[i] = strtod ( input, &next);
                if ( next == input) {//could not parse a double
                    *next = '\0';
                }
            }
            else {
                fprintf ( stderr, "problem fgets\n");
                return 0;
            }
        } while ( '\n' != *next);//repeat loop if next is not a newline
        printf("\n");
    }
    for(i=0; i < n; i++) {//print the doubles with precision of 2
        printf ( "%d %.2f\n", i + 1, sale[i]);
    }
    return 0;
}

它會跳過,因為您在格式字符串中使用了精度字段。
檢查此答案: https : //stackoverflow.com/a/29095617/9986735

這個原型遵循scanf的格式說明符: %[*] [width] [length] specifier
scanf中沒有精度字段。

只需使用: scanf("%lf", &sale[i]); 代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM