我在C中使用pow和sqrt函数是否有问题?

时间:2018-07-14 16:22:34

标签: c

shrt = r - sqrt(pow(x * 1.0, 2.0) + pow(y * 1.0, 2.0));

我使用此代码获取 shrt = r-平方根(x 2 + y 2 的结果。但是我得到的答案是错误的。我的代码有什么问题?当我打印shrt时,答案不正确!这是我的代码:

#include <stdio.h>
#include <math.h>

int main() {
    int i, x, y, r;
    double shrt, lng;
    for (i = 0; i < 100; i++) {
        scanf("%d %d %d", &x, &y, &r);
        shrt = r - sqrt(pow(x * 1.0, 2.0) + pow(y * 1.0, 2.0));
        lng = 2 * r - shrt;
        printf("%.02lf %.02lf\n", shrt, lng);
    }
    return 0;
}

如果我运行代码并在此处输入作为第一个测试用例:0 0 100。然后我得到输出-3.00 -3.00。但是我想要输出100.00 100.00

2 个答案:

答案 0 :(得分:1)

您的scanf失败

在没有它的情况下对其进行测试,您将获得正确的结果:

#include<stdio.h>
#include<math.h>

int main()
{
  int i,x=0,y=0,r=100;
  double shrt,lng;
  for(i=0; i<100; i++)
  {

      shrt=r-sqrt(pow(x*1.0,2.0)+pow(y*1.0,2.0));
      lng=2*r-shrt;
      printf("%.02f %.02f\n",shrt,lng);
  }


  return 0;
}

https://ideone.com/VqdUVI

答案 1 :(得分:0)

您的计算结果取决于xyrshrt的实际类型,以及是否正确定义了sqrt和{{1 }}函数。

最可能导致错误结果的原因是缺乏对powsqrt的正确定义。确保源文件的开头出现以下行:

pow
相关问题