【问题标题】:Error while using sqrt in C++在 C++ 中使用 sqrt 时出错
【发布时间】:2016-02-03 05:16:34
【问题描述】:

我正在为我的统计类编写一个计算器,但我的代码有问题。这是为了计算置信区间。当我使用sqrt 时,我收到“错误不止一个重载函数实例”。还有一些我无法识别的其他问题。我正在使用 Visual Studio 2010 并使用 win32 控制台应用程序。如果你能帮助我,那会很有帮助。 (我是编码新手,所以请忍受我糟糕的编码。)

  #include "stdafx.h"
  #include <cstdlib>
  #include <stdio.h>
  #include <math.h>
  #pragma warning(disable: 4996)

  int _tmain(int argc, _TCHAR* argv[])
 {
   double sample = 0, z = 0, sample1 = 0;
   double std = 0, error = 0, sampleroot = 0, error1 = 0;

   printf("What is the Z score?");
   scanf("%d\n", &z);

printf("What is the std?");
scanf("%lf\n", &std);

printf("What is the sample size?");
scanf("%d\n", &sample);

printf("What is the Error?");
scanf("%lf", &error);

//sampleroot = sqrt(sample);
error1 = z * (std/sqrt((double)sample));
sample1 = ((z * std) / error) * ((z * std) / error);

printf("Error = %lf\n", error1);
printf("Sample is %d\n", sample1);


system("pause");
return 0;
  }

那是我的新代码。当我运行它时,它只询问前 3 个 printfs 并直接跳到解决方案。我该如何解决这个问题。

【问题讨论】:

  • 请注意,&lt;cstdlib&gt; 是纯 C++ 头文件,不能在 C 程序中正常使用。重载也是 C++ 中的一个问题,而不是 C 中的问题; C 中没有重载函数。因此,您不是在 C 中工作——您是在 C++ 模式下使用 C++ 编译器,而不是在 C 模式下,如果您在编译附近得到它的话。
  • scanf("%d\n", &amp;z); remove \n --> scanf("%d", &amp;z);

标签: c++ statistics calculator


【解决方案1】:

C++中有三个sqrt函数:

double sqrt(double _X);
float sqrt(float _X);
long double sqrt(long double _X);

您已将 sample 声明为 int(可以转换为 float 或 double),因此编译器不知道要调用哪个函数。

您可以选择一个您想要的类型并进行类型转换,sqrt((double)sample),或者您可能只想在开始时将 sample 声明为 double。事实上,您可能希望您的所有ints 都是doubles。

编辑scanf("%lf", &amp;error); 中,您需要在error 之前添加一个&amp;,而且我认为您需要从scanf() 格式中删除所有\n

【讨论】:

  • 我插入了 sqrt((double)sample) 但仍然在 Stats.exe 中的 0x0f9700d8 (msvcr100d.dll) 处得到未处理的异常:0xC0000005:访问冲突写入位置 0x00000000。
  • 您需要在此声明中使用&amp; scanf("%lf", &amp;error);
【解决方案2】:

感谢大家帮助我。如果有人想用它来查找置信区间中的错误和样本量,这里是工作代码。

#include "stdafx.h"
#include <cstdlib>
#include <stdio.h>
#include <math.h>
#pragma warning(disable: 4996)

int _tmain(int argc, _TCHAR* argv[])
{
double sample = 0, z = 0, sample1 = 0;
double std = 0, error = 0, sampleroot = 0, error1 = 0;

printf("What is the Z score?");
scanf("%lf", &z);

printf("What is the std?");
scanf("%lf", &std);

printf("What is the sample size?");
scanf("%lf", &sample);

printf("What is the Error?");
scanf("%lf", &error);

//sampleroot = sqrt(sample);
error1 = z * (std/sqrt((double)sample));
sample1 = ((z * std) / error) * ((z * std) / error);

printf("Error = %lf\n", error1);
printf("Sample is %d\n", sample1);


system("pause");
return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多