如何找到数组中的最大数并用c++显示
how to find the largest number in an array and display it in c++
所以我需要将数字输入到一个数组中,并找到并显示最大的数字,我不确定我的循环是否是实现这一点的最佳方法。此外,我不确定如何设置它,我已经尽我所能完成了大部分代码,任何输入都将不胜感激!
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main()
{
// initialize the CONSTANTS
const int SENTINEL = -1;
// initialize the variables
int num1 = 0;
int i;
int sum = 0;
int n;
int a[10];
int largest;
float avg;
/***************************************BEGIN*********************************************/
// Title largest of three revised
cout << setw(25) << "Largest Of Three Revised Program" << "n";
// prompt user for how many numbers they want to input for size of array with -1 to QUIT
cout << setw(25) << "*********************************************" << endl;
cout << setw(25) << "Enter how many elements you want " << SENTINEL << " to quit " << endl;
cout << setw(25) << "*********************************************" << endl;
while (num1 != SENTINEL)
{
// user inputs a number for array size
cin >> setw(45) >> n;
// if number is larger then 10 array is automatically set to 10
if (n>10)
n=10;
// prompts users for numbers to fill the array
cout << setw(45) << "Enter the "<< n <<" array elementsn";
// clear screen
//system("cls");
// puts user input numbers into the array while incrementing the count
for (i=0;i<n;i++)
cin >> setw(45) >> a[i];
// finds the largest number
largest = a[0];
for(i=1;i<n;i++)
{
if (a[i]> largest)
}
largest = a[i];
// adds all the numbers together to find the sum
for (i=0;i<n;i++)
{
sum=sum+a[i];
}
// calculates the average of the sum
avg=sum/n;
// display largest number
cout << setw(45) << "Largest number is: " << largest << "n" << endl;
// displays the sum
cout << setw(45) << "nsum of array elements n"<< sum;
// displays the average
cout << setw(45) << "naverage of array elements n"<< avg <<"n";
//cout <<"0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789n";
return 0;
}
}
尝试此代码以查找数组中的最大数字
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int temp,a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
temp=a[0];
for(int i=1;i<n;i++)
{
if(a[i]>temp)
{
temp=a[i];
}
}
cout << "Largest number is:" << temp <<endl;
return 0;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 密码登录程序将永远循环并显示不正确的结果
- std::strftime 在 Windows 中使用 GMTIME 将时区 UTC 显示为 UTC+1