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

Amazon online assessment coding question to find nth Geometric Progression

本文关键字:几何级数 在线评估 编码 问题 亚马逊      更新时间:2023-10-16

给定几何级数的第二项和第三项。找到它的第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.

您应该首先将您尝试的内容作为问题的一部分。无论如何,为了将双值转换为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;
}