【发布时间】:2018-03-08 21:12:07
【问题描述】:
假设 savings 和 expenses 是已赋予值的 double 类型变量。编写一个 if-else 语句,输出单词 Solvent,将 Savings 的值减去费用的值,并将费用的值设置为 0,前提是储蓄大于费用。但是,如果储蓄少于支出,则 if-else 语句仅输出单词 Bankrupt 并且不会更改任何变量的值。
具体问题:为什么我的程序在我输入储蓄值后会立即跳过?我该如何补救?
#include <stdio.h>
void solvent();
int main(void)
{
double savings, expenses;
printf("\nEnter a number for savings: ");
scanf("%2lf", &savings);
printf("Enter a number for expenses: ");
scanf("%2lf", &expenses);
if(savings > expenses)
solvent();
else
printf("Bankrupt!");
system("pause");
return 0;
}
void solvent(double savings, double expenses)
{
printf("Solvent!");
savings -= expenses;
expenses = 0;
}
【问题讨论】:
-
停止使用scanf。停下来。在学习语言的同时尝试学习是一个可怕的功能。将参数作为命令行参数传递,并使用
fread和fgets读取输入。 -
这一定是个骗子;在
scanf格式中放置一个空格来吃掉空格。 -
从
"%2lf"中删除2。函数scanf与printf有一些相似之处,但又有所不同。另外,请参阅Why not use Double or Float to represent currency? -
@CarlNorum,
%lf将跳过空格。问题可能是用户输入的数字多于 2 位。 -
至少检查一下任何 scanf 系列函数的返回值,我确信这不是被禁止的。如果你不这样做,解析错误会导致非常混乱的行为,通常甚至是未定义的行为......
标签: c