-3

9つのスペース(要素)を持つ配列があり、ユーザーが入力した9つの数値が格納されます。

それらがそれらの9つの数字だけを入力し、それらが同じではないことをどのように確認しますか?
最後にcout(印刷)小さいものから大きいものへ?

4

1 に答える 1

3

[0,9]の範囲の数値を確保し、重複を無視するソリューションは次のとおりです。

#include <algorithm> //if using copy printing
#include <iostream> //for cin and cout
#include <iterator> //if using copy printing
#include <set> //for set

CHOOSE A METHOD BELOW AND ADD THE CORRESPONDING INCLUDE

int main() {
    std::set<int> nums; //here's the array

    std::cout << "Please enter nine different numbers." 
                 "Duplicates will be ignored.\n";

    //ADD THE NEXT PART OF THE METHOD, THE DECLARATION

    do {
        std::cout << "Enter the next number: ";

        //ADD THE FINAL PART, GETTING INPUT AND INSERTING IT INTO THE SET
    } while (nums.size() < 9); //do this until you have 9 numbers

    std::cout << "The numbers you entered, in order, are:\n";

    //C++11 printing
    for (const int i : nums)   
        std::cout << i << ' ';

    //C++03 printing using copy
    std::copy (nums.begin(), nums.end(), 
               std::ostream_iterator<int> (std::cout, " "));

    //C++03 printing using an iterator loop
    for (std::set<int>::const_iterator it = nums.cbegin(); //this was to
                                       it != nums.cend();  //eliminate the
                                       ++it)               //scrollbar
        std::cout << *it << ' ';
}

最初の方法:(より広い範囲に適しています)

#include <limits> //for numeric_limits
...
int temp; //this holds the current entry
...
//works better when you get out of the range 0-9
while (!(std::cin >> temp) || temp < 0 || temp > 9) { 
//body executes if input isn't an int between 0 and 9

    //clear bad input flag
    std::cin.clear(); 

    //discard bad input
    std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 

    //prompt for new number (could also add that you're ignoring to beginning)
    std::cout << "Invalid number. Please enter a new one: "; 
}

//insert the valid number, duplicates ignored, automatically sorted
nums.insert (temp); 

2番目の方法: (0〜9の範囲に適しています)

#include <cctype> //for isdigit
...
char temp; //holds current entry
...
//suitable for 0-9 range 
do {
    std::cin >> temp; 
    if (!std::isdigit (temp))
        std::cout << "Invalid number. Please enter a new one: ";
while (!std::isdigit (temp));

nums.insert (temp - '0'); //add the integer value of the character processed

ここで重要なのはstd::set、一意のエントリのみを許可し、要素を自動的に並べ替えるです。

于 2012-07-18T16:38:42.913 に答える