如何通过根据间隔对字符串进行分组来乘以字符串中的数字?

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

我想得到一串数字除以特定区间并相乘的结果。我知道怎么把一个字符变成一个数字。

这是代码

#include<stdio.h>

int main(void) {
    char str[] = "123456";
    int a, b, c;
    a = str[0] - '0';
    b = 23; // desired to be changed. str[1] ~ str[2]
    c = 456; // desired to be changed. 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);
}

我指定要划分的索引区间为0、1到2、3到5。 不知道怎么把字符转成数字,就直接给变量存值了。

这是输出:1 * 23 * 456 = 10488

这是想要的结果:

  1. 在str中,将index 0对应的数字改为int类型
  2. str中,将index 1到2对应的数字改为int类型
  3. 将str中索引3到5对应的数字改为int类型
  4. 乘以改变的数字。

相关。但是,我很好奇用户是如何故意划分和乘以部分而不是按空格划分的。

要将两位数字符串转换为数字,您需要将第一个数字乘以 10 并添加第二个数字,对于 3 个数字也是如此,如下所示:

#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);
}

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

根据您在步骤 1234 中列举的示例算法,不包括任何用户输入指令,这里是一个提取的实现通过使用字符串解析、复制和字符串到数字转换从源字符串中提取 3 个整数。

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;
}  

输出;

10488