考慮查找最大和最小數:陣列中的
#include <iostream> // Include header file
using namespace std;
int main() //start of main function
{
int values[20]; // Declares array and how many elements
int small, big; // Declares integer
big = small = values[0]; // Assigns element to be highest or lowest value
for (int i = 0; i < 20; i++) // Counts to 20 and prompts the user for a value and stores it
{
cout << "Enter value " << i << ": ";
cin >> values[i];
}
for (int i = 0; i < 20; i++) // Works out the biggest number
{
if(values[i] > big) // Compare biggest value with current element
{
big = values[i];
}
}
for (int i = 0; i < 20; i++) // Works out the smallest number
{
if (values[i] < small) // Compares smallest value with current element
{
small = values[i];
}
}
cout << "The biggest number is " << big << endl; // Prints outs the biggest number
cout << "The smallest number is " << small << endl; // Prints out the smallest number
}
這是到目前爲止我的代碼。我遇到的問題是打印出最大數量的數組。將第一個元素分配給最高值和最低值有關。它是有效的,如果我分開做它們。有什麼建議麼?
你知道,我全部都是爲了評論。但像這樣的評論// include頭文件是一個障礙。將閱讀或評級你的作品的人知道包含指令的作用。 – StoryTeller 2013-04-30 11:39:10
'big = small = values [0]'未定義的行爲,因爲元素沒有定義值。如果在編譯時打開警告,編譯器將生成相應的錯誤消息:'-Wall -Wexra -Werror' – 2013-04-30 12:52:23
@StoryTeller以及其他許多註釋:'// main start',// // delcares array和多少個元素','//聲明整數'... – Shoe 2013-04-30 13:16:41