c - 在函数中使用 scanf 和循环

标签 c function loops if-statement scanf

我想使用一个函数向用户询问余额。如果余额低于 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;
  }

最佳答案

getPositiveValue() 应该返回一个值( float )。您可以添加 return money;在收盘前}。

如果用户特别密集,没有输入正数怎么办?你只想给他们一次机会吗?如果没有,您可能想使用 while (money < 0.0)循环。

关于c - 在函数中使用 scanf 和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504779/

相关文章:

c - Visual Studio 2010 错误# U1095,NMAKE

c - 标准库.h : no such file or directory

function - Julia:带有 Vector 类型可选参数但默认为 null 的函数?

python - 将函数与笔记本目录中其他 python 文件中的变量一起使用

python 字符串插值与另一种方法

html - Swiffy flash 到 html5 的转换不断循环

c - 变量周围的运行时检查失败堆栈已损坏

c - 如何通过mib监控Tuxedo

c - 数组的内存分配

c - mkdir 的隐式声明