Reputation: 91
I want to get the decimal digits separately when I get the number. For example, if I get 123 or 321, I want to sort the array or print the digits "1 2 3" or "3 2 1" in C.
Would you please give me some any advice? Use C grammar?
int nums;
scanf("%d", &nums) // imagin this nums is 123
// and how can I get the number 1,2,3?
In the array. I will sort the number like
for(int i = 0; i<3; i++)
array[i] = nums;
and I expect in the array number is probably {1,2,3};
Upvotes: 0
Views: 3102
Reputation: 257
Version 2 of SayNum: The “% 10”- method works ok if you’re working with positive integers only. With real numbers (floats), things get a bit tricky, so I used a new method based on “sprintf”- function.
void SayNum (double Num, uint8_t Dp) // Say Number Ver 2
{
uint8_t Digit;
char NumStr[20];
sprintf (NumStr,"%1.*f",Dp,Num);
for (int x = 0; x < strlen(NumStr); x++)
{
switch (NumStr[x])
{
case '-':
// Say "Minus" (play mp3 audio file) >>
break;
case '.':
// Say "Point" (play mp3 audio file) >>
break;
case '0' ... '9':
Digit = (int)(NumStr[x]) - 48;
// Say the Digit (play mp3 audio file) >>
break;
}
}
}
With this function you can do positive or negative integers or real numbers. You can also specify how many numbers after the decimal point you want.
Example1 : SayNum(-12,0); // Says the integer -12 (with no decimal places)
Example2 : SayNum(12.34,2); // Says the real number 12.34 (with 2 decimal places)
Upvotes: 0
Reputation: 257
I have an application that uses a mp3 player to announce a number. My “SayNum” function takes a (positive) integer like 123 and say it verbally like “One” … “Two” … “Three”. This is the function >> (simplified , left out the detail of commands to the mp3 player to play the tracks):
void SayNum (int Num) // Say- Number- Function
{
uint8_t Digit;
int DivNum = 1;
while ((DivNum * 10) <= Num) DivNum *= 10;
while (DivNum >= 1)
{
Digit = (Num / DivNum) % 10;
// Say the digit (play mp3 audio file) >>
DivNum /= 10;
}
}
You could easily add an index counter in the while loop and then use it to store each digit in an array.
Upvotes: 0
Reputation: 41017
You can use a recursive function printing the modulo in each call:
#include <stdio.h>
static void print(int value)
{
if (value != 0) {
print(value / 10);
printf("%d, ", value % 10);
}
}
int main(void)
{
int value;
scanf("%d", &value);
print(value);
return 0;
}
input: 123
output: 1, 2, 3,
Upvotes: 2