gpt4 book ai didi

c++ - 亚马逊在线评估编码问题找到第n个几何级数

转载 作者:行者123 更新时间:2023-12-03 07:03:53 25 4
gpt4 key购买 nike

给定几何级数的第二和第三项。找到它的第n个项,并四舍五入至小数点后3位。

我们必须完成以下功能:

char* nthTerm(double input1, double input2, int input3) {
//your code here
}
input1 = 2nd term and input2 = 3rd term and both are between -2 to 2.
input3 = nth term to find and can be up to 100.

我无法在时间限制内将结果从double转换为char数组。测试是在 Mettl平台上进行的,我认为我无法使用to_string(),stringstream等。尽管pow()函数可以正常工作。
e.g input1 = 1, input2 = 2, input3 = 4
output = 4.0

请有人帮忙解决此问题。

我的方法,但得到编译错误和错误的结论:
    double r = input2/input1;
double a = input1/r;
double ans = a * (double)pow(r, (double)(input3-1));
char *result = new char[1000];
// from here i tried so many thing like i used to_string,
// setprecision, maps, etc. But getting errors only.

最佳答案

您应该首先包括您尝试过的部分问题。无论如何,为了将 double 值转换为char指针,可以先使用sprintf将其转换为char数组,然后再将结果转换为char指针。下面的示例代码:

#include <stdio.h>

int main(void) {
char charray[200];
double num = 121.14;
sprintf(charray, "%2.3f", num);
char* c = &charray[0];
printf("%s", c);
return 0;
}

关于c++ - 亚马逊在线评估编码问题找到第n个几何级数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58920888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com