C ++如何检查数组中的元素是否相等?

编程入门 行业动态 更新时间:2024-10-18 16:46:34
本文介绍了C ++如何检查数组中的元素是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个程序,该程序使用for循环检查数组中的所有值是否相等,但是除了不断重复之外,我无法找出if语句检查数组中的每个值是否相等的方法"if a[i] == a[1] && a[i] == a[0]",依此类推.我不想这样做,因为我希望它适用于任何大小的任何数组.任何帮助深表感谢!

I am trying to write a program which checks if all the values in an array are equal using a for loop but I cannot figure out a way for the if statement to check if each value in the array are equal other than constantly repeating "if a[i] == a[1] && a[i] == a[0]" and so on. I do not want to do that as i want it to work for any array of any size. Any help is much appreciated!

for (unsigned i = 0; i < val; i++){ if (a[i] == a[0]) return true; else return false; }

推荐答案

for (unsigned i = 0; i < val; i++) { if (a[i] != a[0]) { return false; } } return true;

应该这样做.

在这种情况下,代码将立即由于不匹配的值而失败.但是,对于匹配的值,它只会继续检查(众所周知,无论如何,我们都需要测试数组的每个元素).一旦完成,它就会知道一切顺利(因为我们没有提早返回)并返回true.

In this case, the code will instantly fail on a non-matching value. However, on a matching value it simply continues checking (as we know we need to test EVERY element of the array no matter what). Once that's done, it knows everything went well (since we didn't return early) and returns true.

更多推荐

C ++如何检查数组中的元素是否相等?

本文发布于:2023-11-29 17:06:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647039.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!