簡體   English   中英

我想編寫一個 C 程序來添加用戶給出的任意數字列表...誰能修復這個程序?

[英]I want to write a C program to add an arbitrary list of numbers given by user...can anyone fix this program?

我想編寫一個 C 程序來添加用戶提供的數字,只要他們想要......任何人都可以修復這個程序嗎?

我嘗試使用 do-while 循環。 還有其他建議可以改進我的代碼嗎? 我無法結束循環。

#include <stdio.h>

int main()
{
    int x=0, sum = 0, y=0, fu;

    printf("first number you want to add:\n");
    scanf("%d", &x);

    printf("next number you want to add:\n");
    scanf("%d", &y);
    x=x+y;


    do
    {
        printf("do you want to add numbers further? \nEnter 0:Yes or 1:No: \n");
        scanf("%d", &fu);
        printf("next number you want to add:\n");
        scanf("%d", &y);
        x=x+y;
    }
    while(fu>0);

        sum=x;

    printf("Sum of all integers = %d\n", sum);

    return 0;
}

你的提示說:

輸入 0:是或 1:否:

因此,如果輸入0 ,您需要繼續該循環:

while(fu == 0);

此外,您不需要在非0輸入之后再取y

if詢問第三個和更多數字並修改您的while

scanf("%d", &fu);
    if(fu == 0) {
        printf("next number you want to add:\n");
        scanf("%d", &y);
        x=x+y;
    }
}
while(fu == 0);

從用戶或文件中獲取任何輸入的關鍵是通過檢查 return來驗證每個輸入。 在您知道輸入是成功還是失敗之前,您不能盲目地使用保存輸入的變量。 否則,如果輸入失敗並且您使用值不確定的變量,則會調用undefined behavior

此外,如果您使用的是格式化輸入函數,例如scanf() ,如果發生匹配失敗,則從stdin提取字符將在該點停止,導致失敗的字符留在stdin -- 未讀,只是等待再次咬你在您下一次嘗試輸入時。

相反,如果您使用面向行的輸入函數,例如fgets()或 POSIX getline() ,則一次讀取整行。 您可以簡單地在fgets()填充的緩沖區上調用sscanf()以將數字輸入轉換為整數值。 這樣,轉換成功或失敗都沒有關系,您不會在輸入流中留下任何未讀內容。

正如您必須驗證每個輸入一樣,您也必須驗證每個轉換。 無論是使用sscanf()還是strtol()等......當您未能檢測到轉換失敗時,未能驗證每個轉換可能會導致未定義的行為

使用fgets()getline()另一個好處是它們從用戶按Enter讀取和存儲'\\n' 因此,不必提示"do you want to add numbers further? \\nEnter 0:Yes or 1:No: \\n"而不必擔心另一個輸入和轉換——您只需檢查是否在空白處按下Enter行以了解用戶完成的輸入(例如fgets()歸檔的緩沖區中的第一個字符是'\\n'字符)。

您還必須正確處理無效輸入。 如果用戶輸入"bananas"而不是數字會怎樣?

總而言之,你可以做類似的事情:

#include <stdio.h>

#define MAXC 1024           /* if you need a constant, #define one (or more) */

int main (void) {
    
    char buf[MAXC];         /* buffer (character array) to hold all user input */
    int sum = 0, n = 0;     /* sum and count of numbers */
    
    puts ("press ENTER alone to exit:\n");      /* display instructions */
    while (1) {                                 /* loop continually */
        int tmp;                                /* temporary int to add to sum */
        /* prompt based on 1st or subsequent number */
        fputs (n ? "next number  : " : "first number : ", stdout);
        /* read and validate input, break on EOF or empty line */
        if (!fgets (buf, MAXC, stdin) || *buf == '\n') {
            puts ("---------------------");
            break;
        }
        /* validate conversion to int */
        if (sscanf (buf, "%d", &tmp) == 1) {    /* on success */
            sum += tmp;                         /* add to sum */
            n += 1;                             /* increment count */
        }
        else    /* handle error */
            fputs ("  error: invalid integer input.\n", stderr);
    }
    
    printf ("         sum : %d\n", sum);        /* output final sum */
}

示例使用/輸出

$ ./bin/sum
press ENTER alone to exit:

first number : 10
next number  : -20
next number  : 30
next number  : -40
next number  : bananas
  error: invalid integer input.
next number  : 50
next number  :
---------------------
         sum : 30

有幾種方法可以解決這個問題,如果您希望用戶能夠每行輸入一個以上的數字,您可以使用strtol()解析buf以提取所有值。 (您可以對sscanf()使用從字符串開頭的偏移量和每次轉換時使用的字符從"%n"說明符執行相同的操作)有很多方法。

如果您還有其他問題,請告訴我。

暫無
暫無

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

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