猿问

第二个 For 循环值取决于第一个 For 循环值

我在以下代码中有两个 for 循环。我希望在执行 for 循环时具有以下值。

  • 当 n = 1 时,o = 0,1

  • 当 n = 2 时,o = 2,3

  • 当 n = 3 时,o = 4,5

  • 当 n = 4 时,o = 6,7

  • 当 n = 5 时,o = 8,9

有可能吗?如果可能,请告诉我如何做。谢谢。

for (int n = 1; n < dates.Count - 1; n++)

{

    for (int o = n; o < n + 2; o++)

    {

        TravelPlanTouristAttractionNWeatherLabel.Text += "<b><ins>Place Number </ins></b>" + "<b><ins>" + o + "</b></ins>" + "<br/>";

        TravelPlanTouristAttractionNWeatherLabel.Text += "<b>Place Name: </b>" + touristAttractionName[o] + "<br/>";

        TravelPlanTouristAttractionNWeatherLabel.Text += "<b>Address: </b>" + touristAttractionFormattedAddress[o] + "<br/>";

        TravelPlanTouristAttractionNWeatherLabel.Text += "<b>Phone Number: </b>" + touristAttractionFormattedPhoneNumber[o] + "<br/>";

        TravelPlanTouristAttractionNWeatherLabel.Text += "<b>International Phone Number: </b>" + touristAttractionInternationalPhoneNumber[o] + "<br/>";

        TravelPlanTouristAttractionNWeatherLabel.Text += "<b>Website: </b>" + touristAttractionWebsite[o] + "<br/>";

        TravelPlanTouristAttractionNWeatherLabel.Text += "<br/>";

        TravelPlanTouristAttractionNWeatherLabel.Text += "<b><ins>Opening Hours</ins></b>" + "<br/>";

        for (int p = 0; p < 7; p++)

        {

            TravelPlanTouristAttractionNWeatherLabel.Text += touristAttractionOpeningHours[o, p] + "<br/>";

        }

    }

}


烙印99
浏览 252回答 3
3回答

月关宝盒

根据您的示例,o在 range 中2*n-2 to 2*n-1,因此您可以使用以下内容:for (int n = 1; n < dates.Count - 1; n++){&nbsp; &nbsp;for (int o = 2*n-2; o < 2*n; o++) {&nbsp; &nbsp; &nbsp; //Do your magic here&nbsp; &nbsp;}}

胡说叔叔

因为我可以在您的要求中看到一个模式。通过这种模式, o 将始终按顺序递增。而 n 将从 1 增加到日期的计数。所以基本上你可以在不计算 n 的任何公式的情况下推导出 o。(确保您是否想从 n = 某个其他数字开始循环,然后您希望 o 应该按照 n 保持初始值,但不会。但我不认为这是您的问题的情况)这样做,int o = 0;for (int n = 1; n < dates.Count - 1; n++){&nbsp; ....&nbsp; &nbsp; &nbsp;for(int k = 0; k < 2; k++)&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // this loop should be running for two iterations only.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //even if loop is on k, use o&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; o++;&nbsp; &nbsp; &nbsp;}}但如果你想建立关系。o 的循环刚好在 2xn 的值之前结束,o 的循环应该运行 2 次。所以相对循环可以从o = (2*n) - 2 到 o < 2*n。for(int o = (2*n) - 2 ; o < 2*n; o++)

斯蒂芬大帝

试试这个 -for (int n = 0; n < dates.Count -1, n++){&nbsp; &nbsp; for (int o = (n-1)*2; o < 2n; o++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Add your logic here :)&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答