简体   繁体   English

在 for 循环中使用 1 个以上的值?

[英]Using more than 1 values in a for loop?

I need help to use a 'for loop' with more than 2 values which are going together.我需要帮助来使用具有超过 2 个值的“for 循环”。 This is my code:这是我的代码:

for( x=1 , y=1 ; x<6 , y<10 ; x++  , y++){
    cout << "x:" << x << endl;
    cout << "y:" << y << endl;

Right now when I run it ... x and y are going up to 9 although I want them to run together but i want x to stop outputting at 6 and i want y to continue to 9..but I don't know how to do it or is it even possible to do so.. Thanks in advance!现在,当我运行它时... x 和 y 将达到 9 虽然我希望它们一起运行但我希望 x 在 6 停止输出,我希望 y 继续到 9 ..但我不知道如何这样做还是有可能这样做..提前致谢!

I don't use c++ so someone correct me if my syntax is wrong, but as a broad-spectrum programmer I'd imagine the solution would look something like this:我不使用c++所以如果我的语法错误,有人会纠正我,但作为一名广谱程序员,我想解决方案看起来像这样:

for (x=1, y=1; x<6 || y<10;) {
    if (x<6) {
        cout << "x:" << x << endl;
        ++x;
    }
    if (y<10) {
        cout << "y:" << y << endl;
        ++y;
    }
}

There are also ways to achieve this affect without leaving the core of your for loop using ternary operators but for the sake of simplicity I've excluded that here.还有一些方法可以在不离开 for 循环核心的情况下使用三元运算符来实现这种效果,但为了简单起见,我在这里排除了它。

test.cpp:测试.cpp:

#include <iostream>
int main() {
    for(int i = 1; i < 6; ++i) {
        std::cout << "x: " << i << std::endl;
        std::cout << "y: " << i << std::endl;
    }
    for(int i = 6; i < 10; ++i) {
        std::cout << "y: " << i << std::endl;
    }
}

Output:输出:

x: 1
y: 1
x: 2
y: 2
x: 3
y: 3
x: 4
y: 4
x: 5
y: 5
y: 6
y: 7
y: 8
y: 9

The simplest, for a natural interpretation of the question, is a nested loop:对于问题的自然解释,最简单的是嵌套循环:

for( int y = 1; y < 10; ++y )
{
    for( int x = 1; x < 6; ++x )
    {
        cout << "x:" << x << endl;
        cout << "y:" << y << endl;
    }
}

If instead you actually want two values called x and y that are always the same, and you want to do one thing for x < 6 and something else for y < 10 , then a single loop counter suffices:相反,如果您实际上想要两个始终相同的xy值,并且您想为x < 6做一件事,为y < 10做另一件事,那么单个循环计数器就足够了:

for( int i = 1; i < 10; ++i )
{
    int const y = i;
    if( i < 6 )
    {
        int const x = i;
        // Do the x and y thing here. E.g.
        cout << "x: " << x << endl;
    }
    // Do the y only thing here. E.g.
    cout << "y: " << y << endl;
}

If you meant something else then you need to clarify your question, eg with an example of desired output.如果您的意思是别的,那么您需要澄清您的问题,例如使用所需输出的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM