【问题标题】:why does the value of this factorial change when called by a function that SHOULD calculate the value of e为什么这个阶乘的值在被应该计算 e 的值的函数调用时发生变化
【发布时间】:2023-01-13 23:10:46
【问题描述】:
#include <stdio.h>
#include <math.h>

int main()
{
    double precision = 0;
    printf("\ninsert number\n");
    while(precision < 1){
        scanf("%lf",&precision);
    }
    printf("the value of e with precision of %.0lf is %lf",precision,e(precision));
    return 0;
}

int fact(int num){
    int ris = 1;
    for(int i = num;i > 0;i--){
        ris = ris * i;
    }
    printf("res=%d\n",ris);
    return ris;
}

int e(double precision){
    double valE = 1;
    for(double i = precision;i > 0 ;i--){
        valE = valE + 1/fact(i);
        printf("\nsame res:%.1lf\n",fact(i));
    }
    return (double)valE;
}

debug

我知道有一个答案,但我的问题是两个函数之间的通信,我知道我可以通过在 main() 中拍打所有内容来解决它

【问题讨论】:

  • 请不要张贴文字图片,将文字张贴为格式正确的文字。您的程序输出是文本。你可以edit你的问题。
  • 我不明白这个程序应该做什么,但也许 e 应该返回 double 而不是 int?也许 main 应该移到 e 下面,这样你就不会隐式声明任何东西?
  • 永远不要使用浮点数作为循环迭代器。一只小鸟私语说浮点数不准确...
  • 你有没有收到任何编译器警告?
  • 一旦我将 int e 函数替换为 double e,它就会停止编译,我认为只需识别 return ad double 就可以完成这项工作

标签: c function


【解决方案1】:

有很多问题。

你想要这个,cmets 中的解释:

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

int fact(int num) {
  int ris = 1;
  for (int i = num; i > 0; i--) {
    ris = ris * i;
  }
  printf("res=%d
", ris);
  return ris;
}

double e(int precision) {
  double valE = 1;
  for (int i = precision; i > 0; i--) {    // use int for loop counters
    valE = valE + 1.0 / fact(i);           // use `1.0` instead of `1`, otherwise an 
                                           // performed integer division will be
    printf("
same res: %d
", fact(i));   // use %d for int^, not %llf
  }
  return valE;                             // (double) cast is useless
}


// put both functions e and fact before main, so they are no longer
// declared implicitely

int main()
{
  int precision = 0;                  // precision should be an int
  printf("
insert number
");
  while (precision < 1) {
    scanf("%d", &precision);          // use %d for int
  }
  printf("the value of e with precision of %d is %lf", precision, e(precision));
  return 0;
}

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 2015-10-16
    • 2012-11-18
    • 2015-03-05
    • 2016-03-15
    • 1970-01-01
    • 2016-09-19
    • 2020-03-04
    相关资源
    最近更新 更多