问题描述
我目前正在从事学期工作,这是我的一部分代码.如您所见,我在使用结构的地方有一些if语句的for循环.我当时正在考虑将此for循环转换为while循环,但是我不太确定该怎么做.也许有人可以给我提示?
I´m currently working on my semester work and this is a piece of my code. As you can see there is a for loop with some if statements where I am working with a structure. I was thinking of converting this for loop onto a while loop but I´m not quite sure how. Maybe someone may give me a hint?
for(X = 1; X <= 100; X++)
{
if(structure[X].number == -1)
{
structure[X].number = number;
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
if(structure[X].number == number)
{
if(structure[X].first_info == -1)
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
}
推荐答案
所有基本循环都包含三个组成部分:
All basic loops have three components:
- 初始值设定项(分配给变量的初始值)
- 条件(我们要检查的值以保持循环状态)
- 修饰符(用于修改变量的内容)
在for循环中,您会注意到这里的所有三个:
With a for loop you notice all three of those here:
for(X = 1; X <= 100; X++)
括号中的第一个成分是初始化程序(X = 1),下一个成分是条件(X< = 100),最后一个成分是修饰符(X ++).
The first component in the parentheses is an initializer (X=1), the next component is the condition (X <= 100), and the last component is the modifier (X++).
我们可以在while循环中使用完全相同的组件.我们只是将它们放置在不同的位置:
We can use the exact same components with a while loop. We just place them differently:
int x = 1; //our intializer
while (x <= 100){ //our condition
if(structure[X].number == -1)
{
structure[X].number = number;
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
if(structure[X].number == number)
{
if(structure[X].first_info == -1){
structure[X].first_info = position;
}
structure[X].second_info = position;
break;
}
x++; //our modifier
}
话虽如此,C中的数组始终从索引0开始.我将代码保持不变,但是通常,无论您使用的是for循环还是while循环,您都需要按以下方式更改初始化程序和条件:
With that said, arrays in C always start at index 0. I kept your code the same as you had it, but generally whether you are using a for loop or while loop you will want to change your initializer and condition as follows:
- 您的初始值设定项应为x = 0(而不是x = 1) 您的条件可能应该是x<100或x< = 99(不是x< = 100)
- your initializer should likely be x = 0 (not x = 1)
- your condition should likely be either x < 100 or x <= 99 (not x <= 100)
这是因为包含100个项目的数组将具有从0到99的索引.
This is because an array of 100 items will have indexes 0 to 99.
还有两点:
在像这样的索引数组中进行计数时,通常将代码作为for循环而不是while循环更容易阅读.您是否有理由要使用while循环?
When counting through an indexed array like this the code is usually easier to read as a for loop rather than a while loop. Is there a reason that you were wanting to use a while loop instead?
根据您的缩进,尚不清楚最后一个if子句中应包含什么内容.我在您的最后一个if子句中添加了花括号,以使其更易于阅读,但是花括号中可能还应该包含其他行?
Based on your indentation it was unclear what should be included in the last if clause. I have added braces to your last if clause to make it easier to read, but maybe other lines should have been included in the braces as well?
这篇关于将"for"转换为循环到"while"循环环形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!