一、請利用 Java 或 C++實做一完整程式,可以將命令行(command line)傳入之一系列
表示整數的字串轉換成整數,再求其和與平均。若其中有資料格式不符,則印出
"Incorrect input!"之後停止程式執行,否則,請計算出這些數字的和與平均之後,再
將結果印出。平均值為浮點數,請利用無條件捨去法,取到小數第一位。以下是利
用 Java 實作時的執行範例:假設程式檔為 P1Solution,
>java P1Solution 88 90 100
The sum is 278.
The average is 92.6.
>java P1Solution 88 9A 100
Incorrect Input!
(20 分)
詳解 (共 1 筆)
詳解
#include <iostream>
#include <cstdlib> // for atoi
using namespace std;
#include <cstdlib> // for atoi
using namespace std;
int main(int argc, char* argv[]) {
int sum = 0;
try {
for (int i = 1; i < argc; ++i) {
// Check if the conversion from string to integer is successful
char* end;
long val = strtol(argv[i], &end, 10);
if (*end != '\0' || end == argv[i]) throw invalid_argument("Invalid input");
sum += val;
}
double average = static_cast<double>(sum) / (argc - 1);
cout << "The sum is " << sum << "." << endl;
cout << "The average is " << fixed << setprecision(1) << average << "." << endl;
} catch (const invalid_argument& e) {
cout << "Incorrect Input!" << endl;
return 1; // Non-zero return value to indicate error
}
return 0; // Success
}
int sum = 0;
try {
for (int i = 1; i < argc; ++i) {
// Check if the conversion from string to integer is successful
char* end;
long val = strtol(argv[i], &end, 10);
if (*end != '\0' || end == argv[i]) throw invalid_argument("Invalid input");
sum += val;
}
double average = static_cast<double>(sum) / (argc - 1);
cout << "The sum is " << sum << "." << endl;
cout << "The average is " << fixed << setprecision(1) << average << "." << endl;
} catch (const invalid_argument& e) {
cout << "Incorrect Input!" << endl;
return 1; // Non-zero return value to indicate error
}
return 0; // Success
}