试图在c ++接收错误消息时使用sin

时间:2014-12-04 02:43:24

标签: c++ programming-languages trigonometry

尝试编写我使用sin的程序,但我一直收到错误消息

“罪

错误:多个重载函数“sin”的实例与参数列表“

匹配

知道我做错了吗?

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

#define DEGREE 45
#define THREE 3

int
    main(void)
{
    double diagonal;
    double length;
    double volume;
    double stands;
    double volumeostands;

//Get # of stands
    printf("How many stands will you be making? \n");
    scanf("%d", &stands);

//Get diagonal//
    printf("What is the diagonal of the cube? \n");
    scanf("%d", &diagonal);

//Find length

    length = diagonal * sin(double(DEGREE);

//Find volume

    volume = 3(length);
//Multiply volume by number of stands

    volumeostands = volume * stands;

//Display volume (for # of stands)

    printf("Volume is %lf inches for %lf stands", &volumeostands, &stands);


        return (0);
}

2 个答案:

答案 0 :(得分:3)

当编译器无法找出哪个重载函数来调用你的参数时,你得到的错误信息是通常与类型促销或转换有关。例如,您可能有:

void fn(double d);
void fn(float f);

并且,如果您致电fn(x)其中x既不是float也不是double,但同样可以成为其中一种类型,编译器不知道该选哪个。以下程序显示了此方案:

#include <iostream>
int x(double d) { return 1; }
int x(float f) { return 2; }
int main(){
    std::cout << x(42) << '\n';
    return 0;
}

使用g++进行编译会导致:

qq.cpp: In function ‘int main()’:
qq.cpp:5:20: error: call of overloaded ‘x(int)’ is ambiguous
   std::cout << x(42) << '\n';
                    ^
qq.cpp:5:20: note: candidates are:
qq.cpp:2:5: note: int x(double)
 int x(double d) { return 1; }
     ^
qq.cpp:3:5: note: int x(float)
 int x(float f) { return 2; }

因为您传递的int值可能同样成为floatdouble,所以编译器会抱怨。一个快速解决方法是将类型强制转换为特定类型,例如:

std::cout << x((double)42) << '\n';

对于特定的情况,它可能正是我所展示的,因为您使用整数类型调用sin()。在C ++ 11之前,唯一的重载是floatdoublelong double。 C ++ 11为整数类型引入了重载,将它们提升为double但是,如果你不是 on C ++ 11,只需使用上面显示的转换技巧。

如果的情况(使用整数类型),你应该意识到的第一件事是sin()将其参数作为 radians 的数量而不是比度,所以你几乎肯定会想要使用浮点(圆圈有360°,但只有2π弧度)。

答案 1 :(得分:-1)

#include <stdio.h>

#include<iostream>

#include <math.h>

using namespace std;

#define DEGREE 45

#define THREE 3

int main(void) {

double diagonal;
double length;
double volume;
double stands;
double volumeostands;

//Get # of stands
cout << "How many stands will you be making? \n" ;
cin >> stands;

//Get diagonal//
cout << "What is the diagonal of the cube? \n" ;
cin >>  diagonal;

//Find length

length = diagonal * sin(DEGREE);

//Find volume

volume = 3*length;
//Multiply volume by number of stands

volumeostands = volume * stands;

//Display volume (for # of stands)

cout << "Volume is " << volumeostands << " inches for stands " << stands << endl;

system("pause");
return 0;

}