For example, given the number 123456789, you need to divide it into separate numbers, 1, 2, 3, 4, 5, 6, 7, 8, 9, so that you can assign them to some variable later. And what is the name of this process itself, in order to read more about this function later.
9 answers
Easy way
#include <stdio.h> #include <stdlib.h> #include <string.h> main () { int num = 12345678, idig = 5; char digs[20]; sprintf(digs, "%d", num); if (strlen(digs) > idig) printf ("%d-th digit in %d is '%c'\n", idig, num, digs[idig - 1]); else printf ("there is no %d-th digit in %d\n", idig, num); } To be honest, I find it difficult to understand the meaning of these lines:
sprintf(digs,"%d",num); if (strlen(digs) > idig) printf ("%d-th digit in %d is '%c'\n", idig, num, digs[idig - 1]); else printf ("there is no %d-th digit in %d\n", idig, num);Here I get confused, but rather in the formats (
%).
I briefly describe the incomprehensible places with the formats. Details can be found in man 3 fprintf .
The functions of the printf family ( sprintf() , fprintf() and others) output the value of their arguments as a sequence of characters in accordance with the formats passed to the function argument as a string. printf() prints characters to stdout , fprintf() to the specified FILE * , and sprintf() to a string ( char array) in your program.
The text of the format strings can be divided into the actual formats, “control” (Control) and just characters.
Just the characters are copied to the output "as is."
Control characters control the text output to the terminal (NewLine, Tab, etc.), they are recorded in formats starting with the backslash (“\”) character. For example:
\n- Newline,\t- tabulation,\g- bell (terminal beeps). Also (this is according to the rules for writing string constants in C) you need to write\"to output quotes. If you need to output the character" \ ", then you need to double it:\\.The “%” character in the format string has a special meaning. He begins another format that says in what form the next argument should be displayed and what type it is. For example:
%d- print an argument of typeintas a decimal number,%c- output an argument of typechar(or low byteint) as a character (that is, without conversions),%x- output an argument of typeintas a hexadecimal numberand so on. There are many formats, they are convenient. Read the man and use.
Returning to the incomprehensible places you indicated in the program:
sprintf(digs, "%d", num);forms in thedigsarray a sequence of digits of a number and a variablenumin accordance with the format%d(that is, displays a number in decimal form);if (strlen(digs) > idig)checks if there is a digitidigat all. For example, you want to display the sixth digit of a number, and there is only one digit in the number (for example, 3).printf ("%d-th digit in %d is '%c'\n", idig, num, digs[idig - 1]);output to stdout:- the first
%dis theidigvariable (the number of the digit in the number) as a decimal number, - the second
%dis the variablenumas a decimal number, %cis a character from thedigsarray (the desired digit) "as is".
- the first
I hope, now it became clearer. In general, read, read and read the documentation again.
- Sorry, but this code is not for C unless ??? And at the expense of the book, I will say this. I usually try to solve the task given to me. For this, I am looking for material if I don’t know how to do it, that’s all. That is, I consider specific cases that I encounter. I therefore wrote that as we say, let's say this process or method to find this topic in the book and study it in detail. - navi1893
- Code in C. C ++ compiler also perceives it perfectly, do not worry. If you like cout << tram_ham_pam << ... and in this for you C ++, write with cout. You asked for a simple and clear code. IMHO is nowhere more understandable (of course, you must understand that the character (char) is an 8-bit number in which the ASCII code of the decimal digit is stored). By the way, to convert a decimal digit (from a character) to a number (int), simply subtract the character '0' from this character. I advise you to just read the book carefully from the beginning to the end, and then (at the second reading) start writing programs. - avp 8:49 pm
- @avp, with all due respect, this solution is a quickie. - skegg
- Why Man wants numbers. Let them take them from char *. I do not understand what is bad? Do you need an int array? You can run on the line and do (in the comments showed him how). @mikillskegg, did you intentionally throw a recursion on him? He IMHO in cycles confused. About KISS - probably heard the principle? - avp
- oneAnd who can write this code for c ++? If not difficult. I can't understand some things on b = / - navi1893
Or so
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; void parse (int n, vector<int>& vec) { vec.push_back (n%10); int temp = n / 10; if (temp == 0 ) return; parse (temp, vec); } int main() { int n = 4500345; vector <int> vec; parse (n, vec); copy (vec.rbegin(), vec.rend(), ostream_iterator <int> (cout, " ")); cout << endl; } - you see, is there really no easy way for this task? Here in your code right now, a lot of novelty for a beginner, very. New libraries, etc. Is it possible to solve it easier? Solution for a beginner, let's say. - navi1893
- 2The main thing here is to understand how to determine which digit is in which digit. One of the most elegant solutions is recursion, which I demonstrated. - skegg
#include <stdio.h> /** * Раскладывает целое число в массив цифр * * Функция factor_digits извлекает цифры числа и размещает в заданном * массиве в обратной последовательности, в соответствии с нумерацией * разрядов, то есть элемент массива с индексом нуль получит значение * нулевого разряда (крайней правой цифры) и т.д. В случае, если при * разложении достигнуто заданное третьим параметром максимальное * количество цифр, функция прекращает работу, возвращая нуль, в * противном случае возвращает количество цифр в разложении. * * @param num Число для разложения * @param digits Массив для размещения результата разложения * @param limit Максимально допустимое количество цифр * @returns количество полученных цифр в разложении, * 0, если превышено предельное количество цифр */ int factor_digits(int num, int *digits, int limit) { int digits_count = 0; // Отдельно обрабатываем ситуацию, когда число изначально равно нулю if (num == 0) { digits[0] = 0; return 1; } // Последовательно извлекаем цифры числа, пока они есть while (num > 0 && limit) { // Копируем очередную цифру в массив digits[digits_count++] = num % 10; // Переходим к следующей цифре num /= 10; // Уменьшаем допустимое количество оставшихся цифр limit--; } return num ? 0 : digits_count; } /** * Тестовая программа, демонстрирующая разложение числа на цифры */ int main() { int n = 123456789; // Разложим для примера число 123456789 int factored_number[10]; // Массив для хранения результата int factored_number_len; // Количество цифр в числе int i; // Выполняем разложение factored_number_len = factor_digits(n, factored_number, 10); // Выводим результат на экран for (i = factored_number_len - 1; i >= 0; i--) { printf("%d\n", factored_number[i]); } return 0; } - 1) cout what to output, num? 2) what does "/ =" mean? - navi1893
- The reverse of the digits [] array is added and almost completely good. By the way, it’s also necessary to process negative numbers (after all, the numbers in them are the same as in the positive ones). - avp 7:09 pm
- please answer, but in the end what should withdraw? Can you add this in response? - navi1893 pm
- 0) Added a test program. Since I started writing on pure C, I did not use C ++ constructions at all. Of course, the C ++ compiler will understand this code. <br> 1) The function records the result of the decomposition (digits of the number) using the digits pointer. Pass the array as the second parameter, get the decomposition. As the third parameter, transfer the number of array elements (this parameter does not affect the operation of the algorithm, it only serves as a protection against potential buffer overflow). 2) The expression x / = 10 is equivalent to the expression x = x / 10. - northerner
- 2@avp, I would say not the last digit , but the least significant bit . By definition, the remainder <divider. Given that the divider we have - the basis of the number system, voila, got a figure. Rinse and repeat until the original number> 0 - karmadro4
int i = 1234567890; string nums; stringstream ss; ss << i; ss >> nums; int* numbers = new int[nums.length()]; for(int j = 0; j < nums.length(); j++) { stringstream s; s << nums.c_str()[j]; s >> numbers[j]; } - Sorry for the beauty, I'm sitting on the phone :)) - cheb
- four+1 for the perversion :-) - VladD
void outputdigits(int n) { if (n == 0) return; int d = n % 10; outputdigits(n / 10); cout << d << " "; } - and how is it (this process) is called? I want to study it in detail - navi1893
- 2@ navi1893, recursion?
%- taking the remainder of the division? - Dex - I just have a task, given the number N. It is necessary to find, for example, its 6th digit and output. What will you tell me? - navi1893 pm
- fourIf you are given a specific number (digit) to be found, and all decomposition is not required then everything is much simpler - it is enough to divide this number by 10 to the power of the digit number and take the remainder from division by 10 (digits are numbered from zero from right to left). For example, the number 1234 is given, hundreds are needed - the digit in number 2 is divided. We divide 1234 by 10 ^ 2 - we get 12, we take the remainder from dividing 12 by 10 - we get 2. - northerner
- It’s not true, this formula is not for everyone. Everything will pass, for example, 12345 to find 4. It will not work - navi1893
A function that receives in the first parameter the number from which it is necessary to obtain a specific digit and the second parameter which particular digit from a number must be obtained. Returns the number you need. The number you want to get counts from the end of the number.
/* 1234567890 = число ^------- 8 = цифра которая нужна */ int func(int chislo, size_t offset) { char str_chislo[20]; sprintf(str_chislo, "%d", chislo); // Если нужная цифра больше чем цифр в числе возвращает -1 if (offset > strlen(str_chislo)) { return -1; } for (size_t i = 1; i < offset; i++) { chislo /= 10; } return chislo % 10; } int main() { printf("%d", func(1234567890, 8)); // Вывод будет 3 return 0; } #include<iostream> using namespace std; int main() { double res; int a; cout<<"Input a"<<endl; cin>>a; res=0; do { res=(res+a%10)*10; a=a/10; if (a<10) res=res+a; } while (a>10); cout<<res<<endl; system("pause"); return 0; } - Add an explanation to the code - cache
Well, xs mb someone will help
#include <iostream> #include<conio.h> using namespace std; int main() { int a,b,c; cout << "ведите число " << endl; cin >> a; b = a/10; c = a % 10; cout << "первый цифр " << b << endl; cout << "второй цифр " << c << endl; _getch(); } //и так например a=5846 int a, b, c, d, e, r, t; b = a/1000; //5 c = a%1000; d = c / 100; //8 e = c % 100; r = e / 10; //4 t = e % 10; //6 how much easier I do not know)))). this is to stat my homework robot.
ps if the number x is not certain (they are, you do not know how many numbers there will be) then I do not
- onewhat a horror !!! - Isaev
- lol yes, I’ll probably have to use another one that would work shas I’ll fix it - flemeth wow
- oneThis can help someone only to get the next deuce on programming) - Isaev
- Yes, all robs now I just checked for 2 digits and here 4 it is necessary to take turns in order to cut them down with% - flemeth wow
cin >> i; string s = static_cast<string> i;//ну или по другому преобразуйте. точно не помню cout << s[num]; - 2Have you tried to compile such code? - skegg
- Yes. I worked - sudo97
- 2You are not confused with
boost::lexical_cast? - VladD
digits = map(int, str(n))ordigits = lambda n, result=[]: digits(n//10, [n%10] + result) if n else result or [0]See How to decompose a two-digit number into two single - valued ones - jfs