gpt4 book ai didi

c++ - C++ 中用户定义数组的问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:53 25 4
gpt4 key购买 nike

我正在尝试使用 cin 创建一个数组来定义大小。虽然这似乎可行(基于我目前拥有的东西),但我想做的其他事情似乎都行不通。

例如,我想使用 for 循环来查找数组中最小的整数,因为我需要将它与数组中的所有其他整数进行比较,但无论我在哪里有返回最小值的语句int,它不会这样做。

我做错了什么?

#include <iostream>

using namespace std;

int main(){


int userSize;
cout << "Please define size of array: ";
cin >> userSize;

int *duckArray = new int[userSize];

for (int i = 0; i < userSize; i++) {
cout << "Please enter a number into the array: ";
cin >> duckArray[i];
}

int smallest = duckArray[0];

for (int i = 0; i < userSize; i++){
if (duckArray[i] < smallest){
smallest = duckArray[i];
cout << smallest << endl;
}
}

//cout << smallest << endl;

return 0;
}

最佳答案

如果您更改此代码,您的代码将正常工作:

for (int i = 0; i < userSize; i++){
if (duckArray[i] < smallest){
smallest = duckArray[i];
}
}

cout << smallest << endl;

这将找到并打印输入的最小数字。

关于c++ - C++ 中用户定义数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com