C++程式範例 判別最大值
先輸入幾組數字 如: 3
再輸入一串文字,用空白隔開,如:3 1 2
最後會出現最大數字,在第幾格(0當作地一格),用空白隔開,如3 0
#include <stdio.h>
#include <float.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
int A[20]; // 用來存放所有輸入數字的array
int max = 0; // 最大值
int maxIndex = 0; // 最大值在array的第幾個
char numberbuffer[] = ""; // 需要輸入幾組數字
int number = 0; // 需要輸入幾組數字(整數)
char str[20]; // 存放輸入的數字
//輸入幾組數字
printf("輸出");
gets(numberbuffer);
number = atoi(numberbuffer);
//輸入數字組成的字串(空白分開)
gets(str);
//根據空白分開存每一個數字到array中
char *pStart = str;
char *pEnd = NULL;
int d;
int arrayIndex = 0;
while(1){
d = strtod(pStart, &pEnd);
if(pStart==pEnd) break;
else pStart = pEnd;
//printf("d = %d\n", d);
A[arrayIndex] = d;
//printf("A[arrayIndex] = %d\n", A[arrayIndex] );
arrayIndex++;
}
//用迴圈找每個arrya中的數字和max比較
for(int i = 0; i < number;i++){
//printf("A[i] = %d\n", A[i]);
//printf("max = %d\n", max);
if(A[i] > max){
max = A[i];
maxIndex = i;
}
}
printf("%d %d",max,maxIndex);
system("PAUSE");
return 0;
}