如何比较两个数组的元素C ++? [英] How to compare two array's elements C++?

查看:102
本文介绍了如何比较两个数组的元素C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨大家好,所以我想比较两个数组元素,看看每两个元素之间的值越大



< b>我尝试了什么:



hi guys ,, soo i wanted to compare two arrays elements ,, and see the bigger value between each two elements

What I have tried:

#include <iostream>
using namespace std;
int main()
{
int a[] =  {1, 2, 3, 4};
int b[] =  {0, 1, 5, 6};
for (int i=0;i<4;i++)
{
    for (int j=0;j<4;j++)
    {
        if (a[i] > b[j])
        {
            cout << a[i] << " | ";
        }
        else if (a[i] < b[j])
        {
            cout << b[j] << " | ";
            break;
        }
    }
}
    
    return 0;   
}





i希望获得这样的价值



i wanted to get value like this

1  | 2 | 5  | 6 |



insted我得到这样的


insted i'm getting like this

1 | 5 | 2 | 2 | 5 | 3 | 3 | 5 | 4 | 4 | 5 |

推荐答案

您正在比较<$ c中的每个值$ c> a [] 到 b [] 中的每个值,因为你嵌套了两个for循环。要获得预期的结果,只需要一个用于 -loop并比较 a [] 的相同索引, b [] 彼此。
You're comparing each value in a[] to each value in b[] because you nested two for-loops. To get your expected result you only need a single for-loop and to compare the same indices of a[] and b[] with each other.


仅针对HomeWork的建议:

您应该学会使用调试器尽快。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到有一点它会停止你所期望的。

在Visual Studio 2010中掌握调试 - 初学者指南 [ ^ ]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]



逐步运行代码,检查变量,非常关注程序正在执行的操作。你应该很快找到错误。
Only advice for HomeWork:
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

Run your code step by step, inspect variables, be very attentive to what your program is doing. You should find quickly what is wrong.


这篇关于如何比较两个数组的元素C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆