[英]C - Inputting whilst Looping
我正在嘗試學習C,我寫了一個小程序來計算各種形狀的面積。 這是源代碼:
#include "stdafx.h"
struct entry
{
float x;
float y;
};
void square()
{
printf("\nPlease enter the size of one of the square's sides\n");
struct entry sq;
scanf_s("%f\n", &sq.x);
printf("\nThe area of the square is %.2f\n\n", sq.x * sq.x);
}
void rectangle()
{
printf("\nPlease enter the length and breadth of the rectangle\n");
struct entry rec;
scanf_s("%f\n", &rec.x);
scanf_s("%f\n", &rec.y);
printf("\nThe area of the rectangle is %.2f\n\n", rec.x * rec.y);
}
void triangle()
{
printf("\nPlease enter the width and height of the triangle\n");
struct entry tri;
scanf_s("Width: %f\n", &tri.x);
scanf_s("Height: %f\n", &tri.y);
printf("\nThe area of the triangle is %.2f\n\n", (tri.x * tri.y)/2);
}
void circle()
{
printf("\nPlease enter the radius of the circle\n");
struct entry circ;
scanf_s("%f\n", &circ.x);
printf("\nThe area of the circle is %.2f\n\n", 3.14 * circ.x * circ.x);
}
void main()
{
int input = 0;
do
{
printf("---Area of a Shape---\n\n");
printf("1. Square\n");
printf("2. Rectangle\n");
printf("3. Triangle\n");
printf("4. Circle\n");
printf("5. Exit\n");
printf("\n\n");
printf("Please make a choice\n");
scanf_s("%d", &input);
switch(input)
{
case 1: square();
break;
case 2: rectangle();
break;
case 3: triangle();
break;
case 4: circle();
break;
case 5: printf("\n\nThank you for using this program! Press enter to exit!\n");
break;
default: printf("\nInvalid choice!\n\n");
break;
}
}
while(input != 5);
getchar();
getchar();
}
我對該程序的唯一問題是,在輸入邊的大小以便計算區域之后,它等待我在顯示答案之前輸入另一個數字(進行選擇)。 我不知道問題出在哪里。 我認為在移動到另一個函數之前,C確保它執行手頭的整個函數。 你能幫我解決一下這個問題嗎? 謝謝。
在您的scanf
格式中,
scanf_s("%f\n", &rec.x);
'\\n'
不代表文字'\\n'
,而是代表空白字符的任意序列。 因此, scanf_s
調用不會結束,直到您在數字(和空格)之后輸入非空白字符[輸入可能不會發送到您的程序,直到您之后鍵入換行符]。 只需從格式中刪除'\\n'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.