【问题标题】:scanf("%f",&aa) VS scanf("%f",&aa) in a while loopscanf("%f",&a) VS scanf("%f",&a) 在 while 循环中
【发布时间】:2021-12-16 08:36:31
【问题描述】:

我使用下面的程序来计算我写的数字的绝对值。当aa 变为n 时程序应该停止。

#include <stdio.h>
int main()
{
float a;
char ap;
printf("Start? Press n for no.\n");
scanf("%c",&ap);
while(ap!='n'){
  printf("Give a number\n");
  scanf("%f",&a);
    if(a<0){
    a=-a;
    }
  printf("Abs=%f\n",a);
  printf("Continue? Press n for no.\n");
  scanf("%c",&aa);
}
printf("Exit");
return 0;    
}

程序似乎忽略了while 循环中的scanf("%c",&amp;aa),这是我的问题。 斜体 是输入 粗体 是输出:

开始?按 n 表示否。

给个数字

4

Abs=4.000000

继续?按 n 表示否。

给个数字

5

Abs=5.000000

继续?按 n 表示否。

给个数字

n

Abs=5.000000

继续?按 n 表示否。

退出

当我将scanf("%c",&amp;aa) 替换为scanf(" %c",&amp;aa) 时,问题就解决了(见空格)。此外,当aa 是一个数字时,一切正常。该程序运行良好,当aa 变为0 时停止。

#include <stdio.h>
int main()
{
float a, aa;
printf("Start? Press 0 for no.\n");
scanf("%f",&aa);
while(aa!=0){
  printf("Give a number\n");
  scanf("%f",&a);
    if(a<0){
    a=-a;
    }
  printf("Abs=%f\n",a);
  printf("Continue? Pres 0 for no.\n");
  scanf("%f",&aa);
}
printf("Exit");
return 0;
}

那是什么?

提前致谢!

【问题讨论】:

    标签: c char scanf


    【解决方案1】:

    %c 之前的空格删除所有空格(空格、制表符或换行符)。这意味着%c 没有空格将读取空格,如换行符(\n),空格('')或制表符(\t)。通过在%c之前添加空格,我们是@987654324 @this 并只读取给定的字符。

    【讨论】:

    • scanf("%c",&amp;aa) 在换行符\n 之后。为什么要读这个?
    • scanf() 函数会在尝试解析字符以外的转换之前自动跳过前导空格。字符格式(主要是 %c;还有扫描集 %[…] — 和 %n)是例外;他们不会跳过空格。
    • 我想我明白了...非常感谢!
    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 2020-02-16
    • 2019-10-22
    • 2021-07-06
    • 2013-02-17
    相关资源
    最近更新 更多