[英]How i can handle garbage?
我是C的新手。我正在嘗試編寫一個計算斜邊的程序,但是當我運行它時,我得到了垃圾值,並且我不知道如何處理它。
double Hypotenuse(double base, double perpendicular)
{
double hyp = sqrt((base*base) + (perpendicular*perpendicular));
return hyp;
}
int _tmain(void)
{
double b, p;
printf("Enter the lenght of base\n");
scanf_s("%f",&b);
printf("Enter the lenght of perpendicular\n");
scanf_s("%f",&p);
printf("The hypotenuse of the triangle is %3.3f",Hypotenuse(b,p));
return 0;
}
問題出在您的scanf語句中。 根據經驗法則,應始終對雙精度使用“%lf”。 這完美地工作:
double Hypotenuse(double base, double perpendicular)
{
double hyp = sqrt((base*base) + (perpendicular*perpendicular));
return hyp;
}
int _tmain(void)
{
double b, p;
printf("Enter the lenght of base\n");
scanf_s("%lf",&b);
printf("Enter the lenght of perpendicular\n");
scanf_s("%lf",&p);
printf("The hypotenuse of the triangle is %3.3lf",Hypotenuse(b,p));
return 0;
}
因此,最好的方法是查看代碼中發生了什么或在哪里得到垃圾,這是在所有scanf輸出ex值之后的最佳方法:
double a;
scanf("%f",&a);
printf("a=%f",a); //OR
printf("a=%3.3f",a);
您可以輕松查看問題是否出在您的scanf或其他地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.