台無しに(あなたが解決策をしたくない場合は読んでいない)(C-のような):
#include <iostream>
struct stats {
int max;
int total;
unsigned int counter;
unsigned int even;
unsigned int odd;
};
static void display(struct stats const &stats) {
std::cout << "counter = " << stats.counter << '\n';
std::cout << "even = " << stats.even << '\n';
std::cout << "odd = " << stats.odd << '\n';
std::cout << "max = " << stats.max << '\n';
std::cout << "total = " << stats.total << '\n';
}
static int ask_number(void) {
int number;
std::cout << "Type an integer (type 0 to stop):";
std::cin >> number;
return number;
}
static void do_stats(int const number, struct stats &stats) {
if (number % 2 == 0) {
stats.even++;
}
else {
stats.odd++;
}
stats.total += number;
stats.counter++;
if (number > stats.max) {
stats.max = number;
}
}
int main(void) {
int number = ask_number();
struct stats stats = {number, 0, 0, 0, 0};
while (number != 0) {
do_stats(number, stats);
number = ask_number();
}
display(stats);
return 0;
}
台無しに(あなたが解決策をしたくない場合は読んでいない)(真CPP ):
#include <iostream>
class Number {
public:
static int ask(std::ostream &os, std::istream &is) {
int number;
os << "Type an integer (type 0 to stop):";
is >> number;
return number;
}
void ask_and_replace(std::ostream &os, std::istream &is) {
number = ask(os, is);
}
Number(std::ostream &os, std::istream &is) :
number(ask(os, is))
{
}
public:
int number;
};
class Stats {
public:
Stats(int max) :
max(max),
total(0),
counter(0),
even(0),
odd(0)
{
}
private:
int max;
int total;
unsigned int counter;
unsigned int even;
unsigned int odd;
public:
friend std::ostream& operator<<(std::ostream& os, Stats const &stats);
void run(int const number) {
if (number % 2 == 0) {
even++;
}
else {
odd++;
}
total += number;
counter++;
if (number > max) {
max = number;
}
}
};
std::ostream& operator<<(std::ostream& os, Stats const &stats)
{
os << "counter = " << stats.counter << '\n';
os << "even = " << stats.even << '\n';
os << "odd = " << stats.odd << '\n';
os << "max = " << stats.max << '\n';
os << "total = " << stats.total << '\n';
return os;
}
int main(void) {
Number number(std::cout, std::cin);
Stats stats(number.number);
while (number.number != 0) {
stats.run(number.number);
number.ask_and_replace(std::cout, std::cin);
}
std::cout << stats;
return 0;
}
可変長の配列が必要ですが、「」は使用できません。あなたの先生にパンチしよう! –
Treycos
あなたの 'do'はwhileが短すぎます。 'number'を管理することはできません。 'number == 0'なら止めることを忘れないでください。 – Franck
どこに値を保存しますか?ユーザーの入力数は限られていますか?配列について学んだことはありますか? – Treycos