c++ - 我的 if 语句逻辑有什么问题?

标签 c++ if-statement logic

在这个小程序中,我尝试按降序排列 3 个数字。但似乎其中有“//3 2 1 - 不起作用”的行作为评论没有按预期工作。看来我的逻辑是对的。

我的输入: 4、 554和 454545

输出:(这不是我想要的) 554、454545 和 4

如果整数 numbThree 的值大于 numbOne,并且如果 numbOne NOT 大于 numbTwo(NOT == else),它应该输出 numbThree、numbTwo 和numbOne 这个顺序,为什么不行呢?

#include <iostream>

int main() {
int numbOne = 0, numbTwo = 0, numbThree = 0;
std::cin >> numbOne >> numbTwo >> numbThree;

if (numbOne > numbTwo) {
    if (numbTwo > numbThree) {
        std::cout << numbOne << " " << numbTwo << " " << numbThree << std::endl; // 1 2 3
    }
    else {
        std::cout << numbOne << " " << numbThree << " " << numbTwo<< std::endl; // 1 3 2
    }
}
else if (numbTwo > numbOne) {
    if (numbOne > numbThree) {
        std::cout << numbTwo << " " << numbOne << " " << numbThree << std::endl; // 2 1 3 - works
    }
    else {
        std::cout << numbTwo << " " << numbThree << " " << numbOne << std::endl; // 2 3 1
    }
}
else if (numbThree > numbOne) {
    if (numbOne > numbTwo) {
        std::cout << numbThree << " " << numbOne << " " << numbTwo << std::endl; // 3 1 2
    }
    else {
        std::cout << numbThree << " " << numbTwo << " " << numbOne << std::endl; // 3 2 1 - doesn't work
    }
}

std::cin.get();
std::cin.ignore();
return 0;
}

在此先感谢您帮助我。

最佳答案

一般来说,您不能通过 2 次比较对 3 个数字进行排序(在信息内容方面有充分的理由,请参阅 YSC 的评论)。您的案例 1 3 2 已经存在缺陷:如果 numbThree > numbOne 怎么办?

一般来说,您最多只能进行 3 次比较。当然,您可以简单地使用标准库(即语言)提供的排序功能。如果您不想(出于某种原因),那么正确的逻辑(升序)是

if(a<b)
  if     (b<c) // a,b,c   // 2 comparisons
  else if(a<c) // a,c,b   // 3 comparisons
  else         // c,a,b   // 3 comparisons
else
  if(    (a<c) // b,a,c   // 2 comparisons
  else if(b<c) // b,c,a   // 3 comparisons
  else         // c,b,a   // 3 comparisons

因此,在 6 种可能情况中的 4 种情况下,我们需要进行 3 次而不是 2 次比较。

关于c++ - 我的 if 语句逻辑有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866757/

相关文章:

java - 基于 jobject 调用 java 方法失败(无效引用?)

c++ - 了解 C++ 0x 特性

javascript - 如何在 javascript 中将 if else 条件添加到数组中(已编辑)

python - 将数组中连续相等的数字设置为零

prolog - 快速在 Prolog 中运行

JQuery 改变每次点击选择的背景

C++:如何将unicode字符打印到文本文件

c++ - 最初宣布为持续困惑

python - 如何将 torch.device ('cuda' if torch.cuda.is_available() else 'cpu' ) 写成完整的 if else 语句?

vb.net - 验证字符串不包含已知值之外的值 [VB.NET]