【问题标题】:Power function runtime error [closed]幂函数运行时错误[关闭]
【发布时间】:2013-06-14 06:19:26
【问题描述】:
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main(void)
{
  int x,y,g,f,r,X=0,Y=0;
  double res=0;
  printf("\nEnter the x and y coordinate of the point separated by a space");
  scanf("%d %d",&x,&y);
  printf("\nEnter the coordinates of the center of the circle ");
  scanf("%d %d",&g,&f);
  printf("\nEnter the radius of the circle");
  scanf("%d",r);
  X=x-g;
  Y=y-f;
  res=(pow((double)X,2.0)+pow((double)Y,2.0)-pow((double)r,2.0));
  printf("%lf",res);
  if(res>0)
    printf("\nThe point lies inside the circle");
  else if(!res)
    printf("\nThe point lies on the circle ");
  else if(res>0)
    printf("\nThe point lies outside the circle");
    getch();
  return 0;
}

上面的代码是一个检查点是否在圆内的程序(我被特别要求使用C的幂函数)。我正在使用 MinGW(截至 2013 年 6 月 14 日的最新版本)来编译我的程序 Windows 7 OS。

程序编译没有任何错误或警告。

但是,当我在命令提示符下运行它时,一旦我输入了所有详细信息,程序就会突然终止。由于下一步是计算res,所以我认为使用幂函数存在错误。请指出相关错误。

【问题讨论】:

  • 调试器说什么?
  • 离题,但我知道你被特别要求使用 pow 但不要使用 pow((double)X,2.0),因为你可以简单地写 (double)X*X(下次)。
  • 对不起,我在匆忙中忽略了明显的问题,(ROOKIE HERE)但我想现在无法删除问题

标签: mingw


【解决方案1】:

程序编译没有任何错误或警告

假的

你不会用-Wall 编译,是吗?

quirk.c:12:11: warning: format specifies type 'int *' but the argument has type 'int' [-Wformat]
  scanf("%d",r);
         ~^  ~
quirk.c:12:14: warning: variable 'r' is uninitialized when used here [-Wuninitialized]
  scanf("%d",r);
             ^
quirk.c:5:16: note: initialize the variable 'r' to silence this warning
  int x,y,g,f,r,X=0,Y=0;
               ^
                = 0

C 仍然是一种仅按值传递的语言。为了scanf() 能够修改它的参数,您需要传递一个指向变量的指针。但是,您传递的不是有效指针,而是一个未初始化的整数,然后它会尝试将其作为指针解引用,然后 Boom! 出现段错误。

改变

scanf("%d",r);

scanf("%d", &r);

(并插入一些垂直空间,这将使您的程序可读。)

【讨论】:

    【解决方案2】:

    scanf("%d",r); 应该是scanf("%d", &amp;r);

    总是编译有警告,我的编译器马上指出了问题:

    warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]

    【讨论】: