2017-12-21 10 views
-1
int gas; 
// Input Code 
int user_code; 
std::cout << std::endl; 
std::cout << "Please enter the Code: "; 
std::cin >> user_code; 
std::cout << "The value you entered is " << user_code; 
std::cout << std::endl; 

int array1[16] = { 42011, 42017, 42029, 42045, 
        42091, 42101, 34001, 34005,  
        34007, 34009, 34011, 34015, 
        34033, 10001, 10003, 24015 }; // 0.2387 (23.87%) 

int array2[45] = { 11001, 24003, 24510, 24005, 24009, 
        24013, 24017, 24019, 24021, 24025, 
        24027, 24029, 24031, 24033, 24035, 
        24037, 24041, 24043, 51510, 51013, 
        51043, 51047, 51600, 51059, 51610, 
        51061, 51069, 51630, 51099, 51107, 
        51683, 51685, 51153, 51157, 51177, 
        51179, 51187, 51840, 54003, 54027, 
        54037, 54065, 42001, 42055, 42133 }; //0.2710 (27.10%) 

int * array1_search; 
array1_search = std::find(array1, array1+ 16, user_code); 

int * array2_search; 
array2_search = std::find(array2, array2 + 45, user_code); 


if (array1_search != array1+ 16) { 
    std::cout << "Codefound in Array1: " << *array1_search << '\n'; 
    gas= 0.2387; 

} 

else if (array2_search != array2_search + 45) { 
    std::cout << "Code found in Array2: " << *array2_search << '\n'; 
    gas= 0.2710; 
} 
else { 
    std::cout << "Not found \n"; 
    gas= 0.1506; 
} 

위의 코드가 현재 코드입니다. 사용자가 변수 user_code 값을 입력하고 두 배열 array1 [16] 및 array2 [45]를 반복하려고합니다. 사용자 입력 값이 첫 번째 배열 1에있는 경우 0.2387의 가스를 할당하고 다른 배열 2에 입력 값이있는 경우 0.2710의 가스를 지정하고 어떤 배열에도없는 경우 가스는 0.1506이어야합니다.C++ 숫자에 대한 배열 검색 중 else 문을 찾을 수없는 경우 else 문을 트리거하지 않음

기본적으로 사용자 입력이 포함 된 배열에 따라 값을 지정하고 싶습니다. C++을 처음 접했을 때, 이것에 관해 가장 좋은 방법은 무엇입니까?

array1 또는 array2에있는 숫자를 입력하면 array1 또는 array2에있는 숫자가 올바르게 식별됩니다. 문제는 두 배열 중 하나가 아닌 else 문을 트리거하여 array2에있는 것으로 식별하는 숫자를 입력 할 때 발생합니다. 예를 들어, user_code로 12345를 입력하면 "Code found in Array2 : 0"이라고 표시됩니다. 나는 12345가 array2에 포함되어 있지 않다는 것을 안다. 왜 * array2_search가 0으로 할당되었는지 이해할 수 없다. user1 코드가 array1이나 array2에 들어 있지 않으면 else 문으로 간다.

+2

'int'변수에는 분수가 없습니다. 매번 '가스'에 '0'을 지정합니다. – Barmar

+1

'16'및 '45'와 같은 숫자를 모두 하드 코딩하지 마십시오. 명명 된 상수를 선언하십시오. – Barmar

+1

'if (array1_search! = array1 + 16) {'- if (array1_search! = std :: end (array1))'를 사용하십시오. 또한 값으로 '45'와 같은 숫자를 사용하면 실수를하는 것이 매우 쉽습니다. 네가 '44'항목을 가지고 있고, 당신이 잘못 계산하고 45 항목이 있다고 생각하면 어떨까요? 코드는 여전히 컴파일되지만 잘못된 결과로 끝납니다. 대신 컴파일러가 계산하도록하십시오. 즉'int array2 [] = {whatever}; ' – PaulMcKenzie

답변

1
else if (array2_search != array2_search + 45) { 

std::end를 사용

else if (array2_search != array2 + 45) { 

이상이어야 하는가 C++ 11 : 당신이 할 수있게하려면

if (array1_search != std::end(array1)) { 
else if (array2_search != std::end(array2)) { 

그리고 int gas; =>double gas; i뿐만 아니라 부동 소수점 값 저장 ntegers (0.2387과 0.2710은 정수 0을 나타냄). 당신이 C++ (11)의 최소가있을 경우 다음과 같은 일을 할 수있는 표준 컨테이너와 새로운 C++ 기능을 사용

0

:

int main() { 
    // Use Constants Instead of "Hard Coded Values" 
    // If you noticed these are not even needed. 
    // const unsigned code1 = 16; 
    // const unsigned code2 = 45; 

    // Made gas a float instead of an int due to the decimal values 
    // I also initialized it with the default value if the code is 
    // not found in either container. 
    float gas = 0.1506f; // Default Price If Not Found 

    // created your first array as a const std::vector<int> and 
    // used its initializer list to populate its contents: this vector 
    // can not be modified: remove the const if this container 
    // will need to have entries added in the future. 
    const std::vector<int> arr1 { 42011, 42017, 42029, 42045, 
            42091, 42101, 34001, 34005, 
            34007, 34009, 34011, 34015, 
            34033, 10001, 10003, 24015 }; // 0.2387 (23.87%) 

    // did the same for the second array 
    const std::vector<int> arr2 { 11001, 24003, 24510, 24005, 24009, 
            24013, 24017, 24019, 24021, 24025, 
            24027, 24029, 24031, 24033, 24035, 
            24037, 24041, 24043, 51510, 51013, 
            51043, 51047, 51600, 51059, 51610, 
            51061, 51069, 51630, 51099, 51107, 
            51683, 51685, 51153, 51157, 51177, 
            51179, 51187, 51840, 54003, 54027, 
            54037, 54065, 42001, 42055, 42133 }; //0.2710 (27.10%) 

    // No changes made here same basic user I/O. 
    int user_code = 0; 
    std::cout << "Please enter the Code: "; 
    std::cin >> user_code; 
    std::cout << "The value you entered is " << user_code; 
    std::cout << "\n"; 

    // Created 2 flags for later. 
    bool b1found = false; 
    bool b2found = false; 

    // auto for loop ranged based. 
    for (auto code : arr1) { 
     if (code == user_code) { 
      b1found = true; // Set flag 
      gas = 0.2387f; // Set new gas 
      // Output code & gas 
      std::cout << "Code found in Arr1: " << code << '\n'; 
      std::cout << "gas = " << gas << '\n'; 
     } 
    } 

    for (auto code : arr2) { 
     if (code == user_code) { 
      b2found = true; // set flag 
      gas = 0.2710f; // set gas 
      // output code & gas 
      std::cout << "Code found in Arr2: " << code << '\n'; 
      std::cout << "gas = " << gas << '\n'; 
     } 
    } 

    // If code not found in either output "not found" and display default gas 
    if (!b1found && !b2found) { 
     std::cout << "Not found\n"; 
     std::cout << "gas = " << gas << '\n'; 
    } 

    std::cout << "\nPress any key and enter to quit." << std::endl; 
    char c; 
    std::cin >> c; 

    return 0; 
} 

당신은 두 개의 부울 플래그를 제거하여이 좀 더 단순화 할 수 있습니다. arr1 또는 arr2에 값이 변경되면 gas 값이 변경된다는 것을 알고 있습니다. 따라서 변경된 사항이 있는지 확인해야합니다.

// auto for loop ranged based. 
for (auto code : arr1) { 
    if (code == user_code) { 
     gas = 0.2387f; // Set new gas 
     // Output code & gas 
     std::cout << "Code found in Arr1: " << code << '\n'; 
     std::cout << "gas = " << gas << '\n'; 
    } 
} 

for (auto code : arr2) { 
    if (code == user_code) { 
     gas = 0.2710f; // set gas 
     // output code & gas 
     std::cout << "Code found in Arr2: " << code << '\n'; 
     std::cout << "gas = " << gas << '\n'; 
    } 
} 

const float defaultGas = 0.1506; 
// If code not found in either output "not found" and display default gas 
if (gas == defaultGas) { 
    std::cout << "Not found\n"; 
    std::cout << "gas = " << gas << '\n'; 
}