簡體   English   中英

我如何才能找到用戶在包含 7 的第二個數組中輸入的數字並打印出來。 C++

[英]How can i find if a number that has been entered by a user on the second array that contains a 7 and print it. C++

所以這是我的代碼。 它的作用是允許用戶從較大的 100 元素陣列制作較小的陣列到較小的自定義陣列。 例如,用戶輸入他們想要一個包含 2 個元素的數組。 現在這 2 個元素可以是他們想要的任何數字,例如 27 或 17。我需要知道如何制作它,以便當用戶輸入一個包含 7 的元素並將其打印出來時。 我知道它需要一個字符串元素,但我已經用盡了所有可能的方法。 我是 c++ 的新用戶。

#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
    int a1, j;
    string numbers[100];
 
    // input from user for the wanted array
    cout << "Enter Wanted Array:" << endl;
 
    for (int a1 = 0; a1 < 100; ++a1) 
    {
        cin >> a1;
        if (a1 > 100) 
        {
            cout << "Array is larger then what is allowed" << endl;
            exit(1);
        }
        else if (a1 < 0) 
        {
            cout << "Array is smaller then what is allowed" << endl;
            exit(1);
        }
        else
        {
            cout << "The Wanted Array is: " << a1 << endl;
        }
 
        cout << "Enter the numbers: " << endl;
 
        //  Input from User for the second Array
        for (int i = 0; i < a1; ++i) 
        {
            cin >> numbers[i];
        }
 
        cout << "The numbers are: ";
        for (int n = 0; n < a1; ++n) 
        {
            cout << numbers[n] << "  ";
        }
    }
    system("pause");
    return 0;
}
 


據我了解,您正在嘗試過濾所有具有數字7的數組元素。

首先,您不需要字符串輸入。 事實上,integer 格式要簡單得多。

這是你如何做的。 對於用戶在數組中輸入的每個數字,運行一個while循環來隔離每個 integer,如下所示:

//  Input from User for the second Array
for (int i = 0; i < a1; ++i) {
    cin >> numbers[i];
    
    int num = numbers[i];
    while(num > 0) {
        int temp = num % 10;
        
        if (temp == 7) {
            cout << numbers[i] << " ";
            break; //to get out of the while loop
        }
        
        temp /= 10;
    }
}

這將打印所有包含數字7的數字。

雖然這會給你想要的結果,但我必須說你的代碼效率很低。 閱讀有關如何編寫高效代碼的更多信息,從長遠來看,它將對您有所幫助。 干杯!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM