'Amazon online assessment coding question to find nth Geometric Progression
Given the 2nd and 3rd term of a Geometric Progression. Find the nth term of it and round it off up to 3 decimal places.
we have to complete the following function:
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.
I was unable to convert the result from double to an array of char in the time limits. The test was on Mettl platform and I think I was unable to use to_string(), stringstream, etc. Although pow() function working fine.
e.g input1 = 1, input2 = 2, input3 = 4
output = 4.0
Please, someone, help on how to solve this problem.
My approach but getting compilation error and wrong verdicts:
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.
Solution 1:[1]
You should first include what you tried as part of the question. Anyway, in order to convert a double value to char pointer, first you can use sprintf to convert it into a char array and then simply convert the result to char pointer. Example code below :
#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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2125722 |
