没有任何数学函数的c ++中的余弦函数

时间:2018-04-01 23:07:15

标签: c++

我正在编写一个代码来计算十进制数的余弦值(以弧度表示)。问题是,当我输入一个小数字时,我只能得到正确的答案。它使用泰勒系列。

double coseno(float x)
{
    double t = x;
    double cos= t;
    for ( int a=1; a<20.0; ++a)
    {
        double mult = -x*x/((2*a)*(2*a-1));
        t *= mult;
        cos += t;
    }
    return cos;
}

2 个答案:

答案 0 :(得分:1)

  1. 你弄错了。在开始时,您应将t设置为1(而不是x);
  2. 你忘记了一个词。如果数字太大或太小,你可以简单地使用一些时间 最终它完美地运作:
  3. import json
    
    def get_input():
    #user input to record in log
        name = input("Name:")
        d = {} #my dictionary
        d['date'] = input('Enter a date in YYYY-MM-DD format:')
        d['hours'] = input("Hours:")
        return name,d
    
    out = {}
    
    name=''
    d=''
    while True:
        exit = input('Do you want to add another input (y/n)?')
        print(exit)
        if exit.lower()=='n':
            break
        else:
            name, d = get_input()
            out[name] = d
            with open(name + '.json','a') as j:
                json.dump(out, j, indent= 2)
            out={}
    #dump into separate file according to name from user input
    
    if name == 'Jessica':
    
        with open('jessica.json','a') as j:
           json.dump(out, j, indent= 2)
    
    else:
        if name == 'Wendy':
            with open('wendy.json','a') as w:
                json.dump(out, w, indent= 2)
        else:
            with open('tat.json','a') as t:
                json.dump(out, t, indent= 2)
        enter code here
    

答案 1 :(得分:0)

我认为问题是当你使用/除以不需要的精度评估操作时。当您使用较小的值时,近似值足以获得正确的结果,但是当您使用较大的值时,您会遇到近似问题。

你在for循环中多次重复近似误差,因此随着输入的增加你得到wronger结果