2013-10-09 76 views
0

好吧,所以我必须使用if-else语句来创建一个程序,以便计算输入的数字的正弦,如果它是奇数,或者计算cos如果是偶数,则为数字。我的程序一直失败,我不知道为什么。有人可以给我一个小费,请问我做错了什么?使用if-else语句计算sin和cos的C++

这是我到目前为止所(我的程序不断失败,所以我不知道下一步该怎么做,直到我解决这个问题)

#include<iostream> 
#include<cmath> 
using namespace std; 

void main() 
{ 
    const double pi = 3.1415926535897932384626433832795; 
    int a; 

    cout << "Please type in a 2 digit number : " << endl; 
    cin >> a; 

    if(a % 2 == 0) 
    { 
     cout << "The input is" << a << "It is an even number." << endl; 
     cout << cos(a) << endl; 
    } 
    else 
    { 
     cout << "The input is" << a << "It is an odd number." << endl; 
     cout << sin(a) << endl; 
    } 
} // main 
+3

'我的程序保持失败',用什么方式**失败?我没有看到明显的错误。为什么我们不得不一直问这个我不知道。 – john

+0

@john我如何找出失败的方式? –

+0

也许你正在进入学位课程? C++ sin/cos期望弧度 – BeniBela

回答

2

要小心,正弦和余弦函数采取浮动或双输入参数。所以你想是这样的:

cout << cos(static_cast<double>(a)) << endl; 

How the cos function is working

+0

该转换自动发生。 – john

+0

这应该或者只是稍微提高结果的准确性(如果存在'double'重载)或者什么也不改变(因为只有一个'double'定义,并且这个改变只会隐式地提升显式)。我需要比我知道哪个标准库更好。 – delnan

+1

很确定'int'没有'cos'重载。 – john

1

看来你希望你的程序输入是在度,但是这是一个问题,因为sincos使用弧度。所以你必须像这样转换

cout << "The input is" << a << "It is an even number." << endl; 
    double radians = (a/180.0)*pi; 
    cout << cos(radians) << endl; 

对于奇数也是如此。

+0

非常感谢! –