I've been trying to find the first digit of the user input without using loops. I did try to apply methods here ( https://codeforwin.org/2015/06/how-to-find-first-and-last-digit-of-any-number.html ) but it seems like I am getting core dumped error before entering the second function. Below is my code. Any help would be greatly appreciated...
#include <stdio.h>
#include <math.h>
void takeInput (int *input);
void firstDigit (int *input, int *digit1);
int main (void)
{
//local declarations
int input; //user input, number from -99999 to 99999
int digit1;
int digit2;
int digit3;
int digit4;
int digit5;
takeInput (&input);
firstDigit (&input, &digit1);
return 0;
}
void takeInput (int *input)
{
printf("type input in -> ");
scanf("%d", input);
return;
}
void firstDigit (int *input, int *digit1)
{
int temp;
printf("firstDigit ");
temp = *input % 10000;
digit1 = *input - temp;
*input = *input % 10000;
// printf("%d", *input);
// temp = (int) log10(*input);
// digit1 = (int) (*input / pow(10, temp));
printf("%d", *digit1);
return;
}
you can convert it to string and then finding first and last digit.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char string[20];
int input;
scanf("%d", &input);
itoa(input, string, 10);
printf("first digit: %d\n", string[0] - '0');
printf("last digit: %d\n", string[strlen(string) - 1] - '0');
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.