简体   繁体   English

在 C++ 中按升序打印多个数字

[英]print multiple numbers in ascending order in C++

So I'm working on this project where I have to gather 2 integers from a user 3 times (loop), and each time I have to print the two integers in ascending order.所以我正在做这个项目,我必须从用户那里收集 2 个整数 3 次(循环),每次我必须按升序打印这两个整数。 The restriction is that you can only have two cout statements within your loop (one is asking for their input and the second is outputting the ascending order).限制是循环中只能有两个 cout 语句(一个是要求输入,第二个是输出升序)。

My only issue with that is, when I think about ascending order, I would do it like (which has two count statements):我唯一的问题是,当我考虑升序时,我会这样做(有两个计数语句):

if (m<n) {
cout << m << n << endl;
if (m>n){
cout << n << m << endl;

So far, this is what I have:到目前为止,这就是我所拥有的:

#include <iostream>
using namespace std;

int main(int,char**) {

int n, m, z;

for (n=0;n<3;n++){

    cout << "Give me two numbers: ";
    cin >> m;
    cin >> z;
    //if (m>z);
    //cout << m << z << "sorted is: " << m << z << endl;
    // This is where I'm getting stuck because I need two count statements to organize in ascending order as shown above
}

}

So have you considered to change which variable holds the lower number?那么你有没有考虑过改变哪个变量持有较低的数字? eg例如

if(m > n){
    int temp = n;
    n = m;
    m = temp;
}

Then you can just use one print然后你可以只使用一张打印

cout << m << " " << n << endl;

This is where I'm getting stuck because I need two count[sic] statements to organize in ascending order as shown above这是我卡住的地方,因为我需要两个 count[sic] 语句按升序组织,如上所示

You have marked this post as C++:您已将此帖子标记为 C++:

Additional options to consider:要考虑的其他选项:

use algorithm lib:使用算法库:

#include <algorithm>

std::cout << std::min(m,n) << " " << std::max(m,n) << std::endl;

or use conditional / ternary operator in your cout:或在您的 cout 中使用条件/三元运算符:

std::cout << ((m<n) ? m : n) << " " << ((n<m) ? m : n) << std::endl;

References are sometimes fun ... but perhaps this challenge is too trivial.参考有时很有趣……但也许这个挑战太微不足道了。

// guess m < n
int& first = m;
int& second = n;

if(!(m<n)) { first = n; second = m; }

std::cout << first << " " << second << std::endl;

Pointers can do the same:指针可以做同样的事情:

// guess m < n
int&  first = &m;
int& second = &n;

if(!(m<n)) { first = &n; second = &m; }

std::cout << *first << " " << *second << std::endl;

or you can use或者你可以使用

  • lambda expressions, or lambda 表达式,或

  • c++ functions, or C++ 函数,或

  • c++ class methods C++类方法

But I think each of these would be directly comparable to either of the first alternatives.但我认为这些中的每一个都可以直接与第一个选择中的任何一个进行比较。

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

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