簡體   English   中英

在函數中使用scanf和循環

[英]Working with scanf and loops in functions

我想使用一個函數來詢問用戶是否有余額。 如果余額低於0,則提示用戶輸入大於0的值。這是我到目前為止所做的代碼:

#include <stdio.h>
#include <string.h>

float getPositiveValue();
int main()
{
  float begbal;
  begbal = getPositiveValue();
  getPositiveValue();
  printf("balance: %f\n", begbal);

  return 0;
}

float getPositiveValue()
{
  float money;
  printf("Please enter the beginning balance: \n");
  scanf("%f", &money);
  if(money < 0)
  {
    printf("Enter a balance amount above 0:");
    scanf("%f", &money);
  }else{

  }
}

我收到錯誤“警告:控制到達非空函數的結束”。 我知道我需要結束else語句,但是如果輸入的值超過0,則不確定要放在那里的內容。此外,當程序運行時,它會要求用戶兩次輸入起始余額。 看起來這應該是一個簡單的修復,由於某種原因我無法理解功能嘿。

任何幫助非常感謝。

修改后的工作代碼(謝謝):

#include <stdio.h>
#include <string.h>

float getPositiveValue();
int main()
{
  float begbal;
  begbal = getPositiveValue();

  printf("balance: %f\n", begbal);

  return 0;
}

float getPositiveValue()
{
  float money;
  printf("Please enter the beginning balance: \n");
  scanf("%f", &money);
 while(money < 0)
  {
    printf("Enter a balance amount above 0:");
    scanf("%f", &money);
  }
        return money;
  }
  1. 您需要返回浮點值,因此在這種情況下您可以返還money
  2. 您在main函數中調用了兩次函數。

     begbal = getPositiveValue(); getPositiveValue(); 

    只需刪除最后一個語句

getPositiveValue()應該返回一個值(float)。 你可以加return money; 在它關閉之前}。

如果用戶特別密集並且沒有輸入正數,該怎么辦? 你想給他們一次機會嗎? 如果沒有,你可能想要使用while (money < 0.0)循環。

“此外,當程序運行時,由於某種原因,它會要求用戶兩次輸入起始余額。”

因為你在你的代碼中調用了函數getPositiveValue() TWICE

並且你的函數需要返回浮點值,在這種情況下是“money”。

用戶可能會堅持輸入錯誤的內容,因此您需要一個循環來迭代,直到他們做對了。 此外,您需要從此函數返回一個值。

float getPositiveValue()
{
    float money;
    fputs("Please enter the beginning balance: ", stdout);
    for (;;) {
        scanf("%f\n", &money);
        if (money >= 0)
            break;
        fputs("Balance must be nonnegative.\n"
              "Please enter the beginning balance: ", stdout);
    }
    return money;
}

但這只是冰山一角。 絕對不應使用scanf不應使用浮點數來跟蹤資金。 什么,你真的應該在這里做是讀一本線與文本的getline (或fgets ,如果getline不可用),並與解析它strtoul和自定義邏輯,大概是作為[$] DDDD [.CC(其中方括號表示可選文本),轉換為uint64_t值,縮放到美分。

由於用戶可能輸入無效范圍(負數)或非數字文本,因此需要在下一個提示之前消耗違規輸入。

float getPositiveValue() {
  float money = 0.0;
  printf("Enter a balance amount above 0:");
  while ((scanf("%f", &money) != 1) || (money < 0)) {
    int ch;
    while (((ch = fgetc(stdin)) != '\n') && (c != EOF));
    if (c == EOF) break;
    printf("Enter a balance amount above 0:");
  }
  return money;
}

暫無
暫無

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

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