[英]C Scanf skipping in Xcode
new guy here.新人来了。 I've been at this for a month or so (C to Obj C to Cocoa to iOS Apps progression)
我已经在这里工作了一个月左右(C 到 Obj C 到 Cocoa 到 iOS 应用程序的进展)
Upon returning to some basic C, I am stumped with the apparently common "scanf skips the next scanf since it's eating the return keystroke" issue.回到一些基本的 C 语言后,我被明显常见的“scanf 跳过下一个 scanf 因为它正在吃回键击”问题难住了。 I've tried adding #c to the second scanf, i've tried adding a space in there too, but it still skips the second scanf and I'm always returning 0 as my average.
我试过在第二个 scanf 中添加 #c,我也试过在那里添加一个空格,但它仍然跳过第二个 scanf 并且我总是返回 0 作为我的平均值。 I know there are better input commands than scanf.
我知道有比 scanf 更好的输入命令。 But for now, there has to be a way to get something as simple as this to work?
但就目前而言,必须有一种方法可以让像这样简单的事情起作用吗?
Thanks!谢谢! ~Steve
~史蒂夫
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));
you should use %d
format specifier to read integer
input.您应该使用
%d
格式说明符来读取integer
输入。
scanf("%d", &x);
scanf("%d", &y);
And Print average by casting to float并通过强制转换为浮动来打印平均值
printf("\nAverage of the two are %6.2f", ((float)(x+y)/2));
Test code:测试代码:
#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;
}
When you hit enter key after entering first number the new line character left on stdin.当您在输入第一个数字后按回车键时,新行字符会留在标准输入上。 Therefore, it takes new line character as next input(second number).
因此,它将新行字符作为下一个输入(第二个数字)。 You should leave a white space before %d in second scanf() function.
您应该在第二个 scanf() 函数中的 %d 之前留一个空格。 scanf(" %d", &y);
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.