Hello everybody. Help with the task. The string contains a record of a natural number in the n-number numeral system (n is specified by the user, 0 <n <10). Get the string containing the decimal notation of this number.
- @Mike, I was looking for. Many that rummaged. I tried to do it through a switch statement, but it does not work. - Serg
- Here, for example, ru.stackoverflow.com/questions/578287/... this is if you need a fully manual translation without using any extraneous functions (you did not specify this in the questions). See how the question is framed at the same time - Mike
- :) k0 * n ^ 0 + k1 * n ^ 1 + k2 * n ^ 2 ..., where k0, k1, k2 are the numbers in the initial number in order, n is the base of the numeration system. 325 in 8 richest = 5 * 8 ^ 0 + 2 * 8 ^ 1 + 3 * 8 ^ 2 = 213 in decimal this is the school course of computer science - Muritiku
- At least you would have specified the question by which means this should be solved, because the strtol given in the answer completely solves your problem, all that remains is to print the number using pritnf (); - Mike
- @Mike by any means. Well, preferably using the string library. I now understand the options that you gave me. But it will be quite difficult. Did you mean strtok? - Serg
|
2 answers
Well, what is a notation on the base n? this
those. the value of a polynomial, which can be simply calculated according to Horner's scheme:
char s[] = "14614235462"; // у вас n < 10 - так что только цифры... int n = 7; // Основание системы счисления int val = 0; for(*c = s; *c; ++*c) { int digit = *c - '0'; // Значение очередной цифры assert(digit >= 0 && digit < n); // Убедиться, что верная цифра val = val*n+ digit; } char out[20]; snprintf(out,"%d",val); All, in the string out - the decimal notation of the original number
|
If you need a ready-made function, for example:
int main() { const char* str = "1234"; int n = ::strtol(str,NULL, 10); const char* str2 = "A"; int n2 = ::strtol(str2, NULL, 16); return 0; } |
