Kar*_*och 5 c arrays int max while-loop
int findMax(int*sums){
int t = 0;
int max = sums[0];
while (sums[t] != '\0'){
printf("current max: %d %d\n", max, sums[t]);
if (sums[t] > max ){
max = sums[t];
}
t ++;
}
return max;
}
Run Code Online (Sandbox Code Playgroud)
这输出:
current max: 7 7
current max: 7 4
current max: 7 2
Run Code Online (Sandbox Code Playgroud)
它忽略了列表的其余部分sums.我认为这是因为下一个元素sums是0.但我不明白为什么它会被0视为'\0'(null).
我确实记得我第一次遇到同样问题的时候(当我试图使用数组构建一个大数字库int时) ,最终我发现与其他答案在技术上 所说的几乎相同'\0' 并且 0 具有相同的价值。
现在这里是2我用来克服这个问题的方法,这些方法仅适用于某些条件
条件:当所有输入元素均为正数时
现在,由于所有输入元素都是正数,因此您可以通过插入负数来标记数组的末尾
通常,我使用-1这种方式:
int a[] = {1, 2, 3, 4, -1}
for(int index = 0; a[index] != -1; index++)
{
//use the array element a[index] for desired purpose!
}
Run Code Online (Sandbox Code Playgroud)相反,您可以输入任何负数并这样做
for(int index = 0; a[index] >= 0; index++)
{
//use the array element a[index] for desired purpose!
}
Run Code Online (Sandbox Code Playgroud)条件:当你的所有元素都绑定在一定范围内时
您现在可能已经明白了:),假设您的所有元素都属于该范围 [-100,100]
您可以在范围边界上方或下方插入任何数字来标记结束...因此在上述情况下,我可以通过输入数字< -100和来标记结束>100。
你可以这样迭代循环:
for(int index = 0; (a[index] > -100) && (a[index] < 100); index++)
{
//use the array element a[index] for desired purpose!
}
Run Code Online (Sandbox Code Playgroud)概括这两种情况,只需在数组末尾放置一个您确定不等于数组元素的值
for(int index = 0; a[index] != value_not_in_array; index++)
{
//use the array element a[index] for desired purpose!
}
Run Code Online (Sandbox Code Playgroud)
因此,现在在情况 1下,您的 while 循环条件可以是以下之一:
while(sums[t] != -1) //typically ended with `-1`
//(or)
while (sums[t] >= 0) //ended with any negative number
Run Code Online (Sandbox Code Playgroud)
在案例 2下:
while ((sums[t] >min_range) && (sums[t] < max_range)) // when elements are bound within a range
Run Code Online (Sandbox Code Playgroud)
或者更一般地说:
while( sums[t] != value_not_in_array )
Run Code Online (Sandbox Code Playgroud)
这两种情况的根本事实是我正在寻找终止
'\0'字符的潜在替代品。
希望这有帮助,编码愉快;)