C Scanf在Xcode中跳过

时间:2013-08-31 15:50:35

标签: c scanf

这里的新人。我已经在这一个月左右(C到Obj C到Cocoa到iOS Apps的进展)

回到一些基本的C后,我很难接受显然常见的“scanf跳过下一个scanf,因为它正在吃返回击键”问题。我已经尝试将#c添加到第二个scanf,我已经尝试在那里添加一个空格,但它仍然跳过第二个scanf并且我总是返回0作为我的平均值。我知道有比scanf更好的输入命令。但就目前而言,必须有一种方法可以让这样简单的东西起作用吗?

谢谢! 〜史蒂夫

int x;
int y;

printf("Enter first number:");
scanf("#i", &x);

printf("Enter second number:");
scanf("#i", &y);

printf("\nAverage of the two are %d", ((x+y)/2));

2 个答案:

答案 0 :(得分:1)

当您输入第一个数字后按Enter键时,stdin上将保留新行字符。因此,它将换行符作为下一个输入(第二个数字)。在第二个scanf()函数中,应在%d之前留一个空格。 scanf(“%d”,&y);

int x;
int y;

printf("Enter first number:");
scanf("%d", &x);

printf("Enter second number:");
scanf(" %d", &y);

printf("\nAverage of the two are %d", ((x+y)/2));

答案 1 :(得分:0)

您应该使用%d格式说明符来阅读integer输入。

scanf("%d", &x); 
scanf("%d", &y);  

通过强制转换为浮动打印平均值

printf("\nAverage of the two are %6.2f", ((float)(x+y)/2));

测试代码:

#include<stdio.h>
int main()
{

int x;
int y;

printf("Enter first number:");
scanf("%d", &x);

printf("Enter second number:");
scanf("%d", &y);

printf("\nAverage of the two are %6.3f\n", ((float)(x+y)/3));
return 0;
}