简体   繁体   English

简单的循环我不知道

[英]Simple for loop I can't figure out

I'm kind of new to C++ so last night I thought of something. 我是C ++的新手,所以昨晚我想到了一些东西。 I want to print out numbers from 1-100 but with 10 numbers per line. 我想打印出1-100之间的数字,但每行10个数字。 I'm aware my code is below is wrong as it just prints 1-100 vertically. 我知道我的代码在下面是错误的,因为它只能垂直打印1-100。 If anyone can shed some light to my question, it would be greatly appreciated. 如果有人可以阐明我的问题,将不胜感激。 Thanks for reading :) 谢谢阅读 :)

#include <iostream>
using namespace std;

int main() {

    for(int x = 1; x <= 100; x++) {
        cout << x << endl;

    }
}

So you want to print 10 numbers, then a carriage return, and then 10 numbers, then a carriage return, and so on, correct? 因此,您要打印10个数字,然后打印回车符,然后打印10个数字,然后打印回车符,依此类推,对吗?

If so, how about something like: 如果是这样,那么类似:

for(int x = 1; x <= 100; x++) {
    cout << x << " ";
    if ((x%10)==0) cout << endl;
}

Use the modulo operator % to determine if a number is a multiple of another: 使用模运算符%可以确定数字是否为另一个的倍数:

for(int x = 1; x <= 100; x++) {
    if( x % 10 == 0 ) cout << endl;
    cout << x << " ";
}

How about 怎么样

int main() {
       for(int x = 1; x <= 100; x++) {
        cout << x << " " ; //Add a space
        if ( x % 10 == 0 ) {
            cout << endl //Put out a new line after every 10th entry?
        }
    }
}

Print new line when it can be device by 10. 如果10可以成为设备,则打印新行。

for(int x = 1; x <= 100; x++) {

    cout << x << ",";

    if ((x % 10) == 0) {

        cout << endl;
    }
}
    for(int i=1; i<=100; i++) {
        i%10==0 ? cout << i<<endl : cout<<i<<" ";
    }

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

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