这个包含模的代码有什么问题?

时间:2019-01-12 12:29:36

标签: c

这里的麻烦是我想让代码正确地说出数字(第一,第二,第三,第二十一,第二十二,第二十三等),而忽略了11,12,13的问题(可以很容易地解决) ,但是为什么这种简单的取模[(i + 1%10)== 1/2/3]只能在1、2和3上使用,而以后再也不能使用,所以它会从else {}中产生“ th”?它应该是直截了当的,但是如果您采用任何数字,例如数组的位置22(22 + 1%10)显然是3!因此它应该满足条件(请注意+1是由于索引0)

for (int i = 0; i < arrLenght; i++)
{
    if (array[i] == key)
    {
        if ((i+1 % 10) == 1)
        {
            printf("bravo! %i is the %ist number of the array! it's address is %p\n", key, i+1, &array[i]);
        }
        else if ((i+1 % 10) == 2)
        {
            printf("bravo! %i is the %ind number of the array! it's address is %p\n", key, i+1, &array[i]);
        }
        else if ((i+1 % 10) == 3)
        {
            printf("bravo! %i is the %ird number of the array! it's address is %p\n", key, i+1, &array[i]);
        }
        else
        {
            printf("bravo! %i is the %ith number of the array! it's address is %p\n", key, i+1, &array[i]);
        }
        return 1;
    }
}

2 个答案:

答案 0 :(得分:1)

它与operator precedence完全相关。要简单地识别它,请尝试以下操作,

printf("%d", 20+1 % 10);   // 21
printf("%d", (20+1) % 10); // 1

答案 1 :(得分:1)

除了错误外,由于运算符%的优先级(与*/相比)的优先级高于+,因此存在一些代码重复,可以避免:

// Use an array to store the superscripts
const char *sup[] = {
 "th", "st", "nd", "rd"
};

for (int i = 0; i < arrLenght; i++)
{
    if (array[i] == key)
    {
        // Evaluate the index, remembering operator precedence
        int idx = (i + 1) % 10;
        if (idx > 3)
        {
            idx = 0;   // Default to 'th'
        }

        printf("bravo! %i is the %i%s number of the array! it's address is %p\n"
              , key, i + 1
              , sup[idx]        // ^^ print the superscript       
              , (void *)&array[i]);  // the format specifier %p requires a (void *) pointer

        return 1;
    }
}