Home > Software design >  A number formed by every k-th digit of another number in c
A number formed by every k-th digit of another number in c

Time:09-28

Given some natural numbers n and k, my goal is to write a C program that outputs a number formed by every k-th digit of n. I wrote a program as follows:

#include <stdio.h>
#include <math.h>
#define MAX 100
  
void printDigit(int n, int k)
{
    int arr[MAX];
    int i = 0;
    int j, r;
  
    while (n != 0) {
        r = n % (int)pow(10,k);
        arr[i] = r;
        i  ;
        n = n / pow(10,k);
    }
  
    for (j = i - 1; j > -1; j--) {
        printf("%d ", arr[j]);
    }
}
  
int main()
{
    int n = 12345678;
    int k = 2;
  
    printDigit(n,k);
    return 0;
}

My code outputs the same number but partitioned into substrings of length k. Why is that and how can I fix it so that I get the number I wanted?

CodePudding user response:

Your logic is too complicated, but if you want to stick to it:

int intpow(int x, int y)
{
    int result = 1;
    while(y--) result *= x;
    return result;
}

void printDigit(int n, int k)
{
    int arr[MAX];
    int i = 0;
    int j, r, powv;
  
    while (n != 0) {
        powv = intpow(10,k -1);
        n /= powv;
        if(!n) break;
        r = n % 10;
        arr[i] = r;
        i  ;
        n = n / 10;
    }
  
    for (j = i - 1; j > -1; j--) {
        printf("%d ", arr[j]);
    }
}

CodePudding user response:

n % (int)pow(10,k) is the low-order k digits of n. If you just want one digit, use n % 10.

Since pow(10, k) returns a double, it might not be an exact integer. You should round it to the nearest integer to do proper division.

void printDigit(int n, int k)
{
    int arr[MAX];
    int i = 0;
    int j, r;
    int divisor = lround(pow(10, k));
  
    while (n != 0) {
        r = n % 10;
        arr[i] = r;
        i  ;
        n = n / divisor;
    }
  
    for (j = i - 1; j > -1; j--) {
        printf("%d ", arr[j]);
    }
}
  • Related