Home > Enterprise >  How can I multiply numbers in a string by grouping them according to intervals?
How can I multiply numbers in a string by grouping them according to intervals?

Time:04-14

I want to get a result of dividing a string of numbers by a specific interval and multiplying it. I know how to change one character into a number.

Here's the code

#include<stdio.h>

int main(void) {
    char str[] = "123456";
    int a, b, c;
    a = str[0] - '0';
    b = 23; // str[1] ~ str[2]
    c = 456; // str[3] ~ str[5]
    printf("%c * %c%c * %c%c%c = %d", str[0], str[1], str[2], str[3], str[4], str[5], a * b * c);
}

I didn't know how to convert characters into numbers, so I stored values directly for the variables.

Here's the output: 1 * 23 * 456 = 10488

Here's the desired result:

  1. In str, change the number corresponding to index 0 to int type.
  2. In str, change the number corresponding to index 1 to 2 to int type.
  3. In str, change the number corresponding to index 3 to 5 to int type.
  4. Multiply the changed numbers.

This question is related. However, I am curious about how the user arbitrarily divides and multiplies the sections rather than dividing them according to spaces.

CodePudding user response:

to convert two digit string into number you need to multiple first digit by 10 and add second digit, the same for 3 digit, something like this:

#include<stdio.h>

// converts number stored between start/end indexes into integer
int parse(char* str, int start, int end) {
    int result = 0;
    for (int i=start; i<=end; i  ) {
        result = result*10   (str[i] - '0');
    }
    return result;
}

int main(void) {
    char str[] = "123456";
    int a, b, c;
    a = parse(str, 0, 0);
    b = parse(str, 1, 2);
    c = parse(str, 3, 5);
    printf("%d * %d * %d = %d", a, b, c, a * b * c);
}

CodePudding user response:

"I didn't know how to convert characters into numbers"

Based on your example algorithm enumerated in steps 1, 2, 3 & 4, without including any user input instructions, here is an implementation that extracts the 3 integers from the source string by using string parsing, copying and string to number conversion.

int main(void)
{   
    char str[] = "123456";
    char num1[10]={0};//note {0} initializes all memory locations in buffer to NULL
    char num2[10]={0};
    char num3[10]={0};
    int n1, n2, n3;
    char *tmp;
    
    //1. In str, change the number corresponding to index 0 to int type
    strncpy(num1, str, 1);
    n1 = atoi(num1);
    //2. In str, change the number corresponding to index 1 to 2 to int type.
    tmp = strchr(str, '2');
    strncpy(num2, tmp, 2);
    n2 = atoi(num2);
    //3. In str, change the number corresponding to index 3 to 5 to int type.
    tmp = strchr(str, '4');
    strncpy(num3, tmp, 3);
    n3 = atoi(num3);

    //4. Multiply the changed numbers.
    int result = n1*n2*n3;
    printf("%d", result);
    
    return 0;
}  

Outputs;

10488
  • Related