繁体   English   中英

C Scanf 在 Xcode 中跳过

[英]C Scanf skipping in Xcode

新人来了。 我已经在这里工作了一个月左右(C 到 Obj C 到 Cocoa 到 iOS 应用程序的进展)

回到一些基本的 C 语言后,我被明显常见的“scanf 跳过下一个 scanf 因为它正在吃回键击”问题难住了。 我试过在第二个 scanf 中添加 #c,我也试过在那里添加一个空格,但它仍然跳过第二个 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));

您应该使用%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;
}

当您在输入第一个数字后按回车键时,新行字符会留在标准输入上。 因此,它将新行字符作为下一个输入(第二个数字)。 您应该在第二个 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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM