gpt4 book ai didi

c - 为什么 scanf 对于 char 输入表现得很奇怪?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:04 25 4
gpt4 key购买 nike

/* Write macro for the following : 

1. Arithmetic Mean of two no.
2. Absolute value of a no.
3. To convert a Uppercase letter to lower case.
4. To obtain bigger of two numbers.

*/

#include<stdio.h>

#define am(a,b) ((a+b)/2)
#define abs(a) (a>=0?a:-a)
#define ul(ch) (ch>=65 && ch<=96 ? ch+32 : ch)
#define bigger(a,b) (a>=b?a:b)

int main () {

int x,y;
char c;

printf("\nEnter two numbers:");
scanf("%d%d",&x,&y);

printf("\nThe arithmetic mean of two numbers is %f",(float)am(x,y));

printf("\nEnter the number:");
scanf("%d",&x);

printf("\nThe absolute value of the number is %d",abs(x));

printf("\nEnter the character:");
scanf("%c",&c);

printf("\nThe letter in lower case is %c",ul(c));

printf("\nEnter two numbers:");
scanf("%d%d",&x,&y);

printf("\nThe bigger of two numbers is %d",bigger(x,y));


return 0;

}

一切正常,只是程序不会因接受字符输入而停止。

这是输出的快照....

  Enter two numbers:4
5
The arithmetic mean of two numbers is 4.000000

Enter the number:-7 **/*After hitting enter here it reaches line no. 7 */**
The absolute value of the number is 7

Enter the character:
The letter in lower case is

Enter two numbers:4 **/*line no. 7*/**
6

The bigger of two numbers is 6

最佳答案

这是因为 %d 跳过了空格,但 %c 没有——换句话说。

%d 将跳过输入流中的任何后续空白,然后输入指针将紧接在最后一位数字之后——这很可能是换行符。因此,当您请求 %c 时,您实际上已经有了输入数据——即您的换行符——这就是您将阅读的内容。

通过在 %c 之前插入一个空格来更改您的 scanf 以要求它跳过空白,所以

   scanf(" %c",&c);

关于c - 为什么 scanf 对于 char 输入表现得很奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7099209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com