【问题标题】:Why does my program not allow me a second input? [duplicate]为什么我的程序不允许我进行第二次输入? [复制]
【发布时间】:2018-03-08 21:12:07
【问题描述】:

假设 savingsexpenses 是已赋予值的 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。停下来。在学习语言的同时尝试学习是一个可怕的功能。将参数作为命令行参数传递,并使用freadfgets 读取输入。
  • 这一定是个骗子;在scanf 格式中放置一个空格来吃掉空格。
  • "%2lf" 中删除2。函数scanfprintf 有一些相似之处,但又有所不同。另外,请参阅Why not use Double or Float to represent currency?
  • @CarlNorum, %lf 将跳过空格。问题可能是用户输入的数字多于 2 位。
  • 至少检查一下任何 scanf 系列函数的返回值,我确信这不是被禁止的。如果你不这样做,解析错误会导致非常混乱的行为,通常甚至是未定义的行为......

标签: c


【解决方案1】:

好的,由于我不太明白的原因,将 %2lf 设置为 %lf 就足以解决此问题。感谢风向标。

【讨论】:

  • 阅读手册页会对您有所帮助。 scanfprintf 家族的功能很复杂,相似又不同,所以需要一些详细的研究来理解它们。
  • 了解什么? Printf 采用浮点数的精度值; scanf 没有。这就是它们的定义方式。
猜你喜欢
  • 2022-11-18
  • 1970-01-01
  • 2013-11-12
  • 2015-04-24
  • 1970-01-01
  • 2021-03-26
  • 2014-05-09
  • 2023-03-07
  • 2014-09-18
相关资源
最近更新 更多