【问题标题】:How to get absolute value for a double value within a function (Without using math.h)如何在函数中获取双精度值的绝对值(不使用 math.h)
【发布时间】:2018-05-09 00:44:33
【问题描述】:

在这种情况下,如何获得双差异的绝对值?

double cos_delta(double x, double delta)
 {
int n = 1;   // n should start with 1 because it is the number of terms

double diff = cos_N(x, n ) - cos_N(x, n - 1);  // n and n-1 instead of n-1 and n-2

********* here ************

while (diff > delta) { // fabs returns absolute value of a double

    n++;
    diff = cos_N(x, n ) - cos_N(x, n - 1);
}
printf("n = %d\n", n);
return cos_N(x, n);

}

【问题讨论】:

  • 为什么不用math.h
  • 因为我无法在这个程序中使用它
  • 这不是问题,这里太容易回答了:double abs(double i) { return i < 0? -i: i; }
  • 但在 C 中,据我所知,您不能在函数中使用派系!我知道这些问题对你们来说很容易,但我正在努力学习
  • 嗯? “不能在函数中使用派系”是什么意思?这与您的问题有什么关系?

标签: c math double absolute arithmetic-expressions


【解决方案1】:

您可以进行比较并输入结果(如果为负双精度值,则在其前面加上一元 -(一元减号),否则该值为正)。

使用简单的if 语句将是处理此问题的最佳方式。

if( dblVal < 0 )
   dblVal =  -dblval;

或者你可以创建一个函数并像这样使用它

double myabs(double d){
    if( d < 0 )
      return -d;
    return d;
}

但最好使用数学库函数fabs() 等。

【讨论】:

  • 如果这是我认为我正在查看的内容,他会在调用fabs() 时收到链接错误。如果他以艰难的方式建立cos() 功率系列,他显然不能调用cos(),所以我认为fabs() 也不存在。另一方面,你确实很好地回答了他的问题。
  • @Joshua.:感谢路过并阅读答案。非常感谢 Anu 建议或在答案中进行编辑。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多