这里的问题是我希望代码正确说出数字(1st,2nd,3rd,21st,22nd,23rd等),更不用说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 %pn", 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 %pn", 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 %pn", key, i+1, &array[i]);
}
else
{
printf("bravo! %i is the %ith number of the array! it's address is %pn", key, i+1, &array[i]);
}
return 1;
}
}
它与运算符优先级完全相关。要简单地识别它,请尝试以下操作,
printf("%d", 20+1 % 10); // 21
printf("%d", (20+1) % 10); // 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 %pn"
, key, i + 1
, sup[idx] // ^^ print the superscript
, (void *)&array[i]); // the format specifier %p requires a (void *) pointer
return 1;
}
}