[英]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.