c - 使用 scanf 输入数字后遇到严重错误

标签 c loops

好吧,我正在用 C 语言编码并使用 Codeblocks。我正在尝试使用泰勒级数来计算 sinh(x) 来练习循环。我的程序运行,但在输入数字后,它遇到严重错误并崩溃。

我相当确定我的错误发生在通过在 getInput 函数中的第一个 scanf 行使用指针来分配值的过程中,这些行有问题:

        printf ("please enter the value of x\n");
        scanf ("%lf", *xPtr);
        printf ("please enter the number of terms you would like to use\n");
        scanf ("%lf", *nPtr);

我的整个乱七八糟的代码如下:

#include <stdio.h>
#include <math.h>
//Global declerations
double x, *xPtr = &x; //declares variable x and the x pointer
double n, *nPtr = &n; //declares variable n and the n pointer

//Function protypes
void getInput ();
double sinHyper ();


/*-------------------------------------------------------------
function: main
Description: calls the funtion getInput to get the input values, the
        value of x and the number of terms (n), from the user.
        main then calls calls the function sinHyper to compute
        the value of sinh(x)

---------------------------------------------------------------*/
void main (shx)
{
  // variable declarations

 getInput();
 double sinhx, *sinhxPtr;

 *sinhxPtr = shx;
 printf("sinh(%.6e)\n", *sinhxPtr);

}

void getInput (void)
{

  printf ("please enter the value of x\n");
  scanf ("%lf", *xPtr);
  printf ("please enter the number of terms you would like to use\n");
  scanf ("%lf", *nPtr);
  while  (*nPtr <= 0 ) {
    printf ("please enter make sure to use at least 1 term(s) for the computation of sinhx \n");
    scanf ("%lf", *nPtr);
  }
}


double sinHyper ()
{
    double shx, *shxPtr = &shx;
    double i;
    i = 1;
    double priorTerm, *pTPtr;   //pTPtr = PriorTermPointer
    pTPtr = &priorTerm;

    do
    {
        if ( i == *nPtr )
            *shxPtr = *xPtr;
        else
            {
            *pTPtr = *xPtr;
            *pTPtr = ((pow((*xPtr), 2))/((2*i+1)*2*i))+(*pTPtr);
                i = i + 1;

                if (i != *nPtr)
                {
                  *pTPtr = ((pow((*xPtr), 2))/((2*i+1)*2*i))+(*pTPtr);
                  i = i + 1;
                }

            }
    }
    while ( i != *nPtr );
    if (*nPtr == 1)
      return shx;

    else
      *shxPtr = *pTPtr;
    return shx;

}

最佳答案

scanf 要求您发送数据保存的地址,例如:

int x;
scanf("%d", &x); // save to address of x

在您的示例中,您需要发送 x 的地址或指针(保存 x 的地址)

关于c - 使用 scanf 输入数字后遇到严重错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46938469/

相关文章:

javascript - js渲染循环一旦满足条件就会中断

c - Mac OS 7-9 - C 编程

c - 读取字符数组

R 循环 :conditioning a loop in R

php - MySQL 和 PHP : Divide two numbers from two different tables with the same date

javascript - gmaps.js - 循环元素并添加标记

c - 以下 for 语句在 C 中产生什么输出?

c - 简单的 VBO 示例存在问题

c - 在套接字编程 C 中,将 Int 值写入服务器会将其转换为 -1

c - 管道上的持久 execvp?