如何重复遍历字符串数组的元素?

How to repeat traverse elements of an string array?

我想计算从二月到一月或十二月到七月的月份,如何重复遍历数组以获得从二月到一月或十二月到七月的统计月份。


char * months[] = {"Jan", "Feb", "Mar", "April", "May", "Jun", 
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    char start_m[5];
    char end_m[5];
    float bill, rate;
    float total;

    
    scanf("%s %s %f %f",start_m, end_m,&bill, &rate);

    int i, start, end;
    for(i = 0; i < 12; i++){
        if(strcmp(months[i], start_m) == 0){
            start = i;
        }

        if(strcmp(months[i], end_m) == 0){
            end = i;
        }
    }

    if(end < start) {
        for(i = start; i < start - end; i++){
            total += (bill * rate);
        }
    } else {
        for(i = start; i < end; i++){
            total += (bill * rate);
        }
    }
    total += bill;
    printf("%.2f", total);

可以使用表达式pos % size进行模运算。一个例子:

int main()
{
    char * months[] = {"Jan", "Feb", "Mar", "April", "May", "Jun", 
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    int size = 12;
    int start = 1;
    
    for(int i = start; i < start + size; i++)
          printf("%d %s\n",i % size, months[i % size]);

    return 0;
}

输出:

1 Feb                                                                                                                                   
2 Mar                                                                                                                                   
3 April                                                                                                                                 
4 May                                                                                                                                   
5 Jun                                                                                                                                   
6 Jul                                                                                                                                   
7 Aug                                                                                                                                   
8 Sep                                                                                                                                   
9 Oct                                                                                                                                   
10 Nov                                                                                                                                  
11 Dec                                                                                                                                  
0 Jan 

这是有效的,因为对于 0 <= i < size,表达式 i % size returns i。对于 i = size,return 0,对于 i = size + 1 returns 1 等等。