簡體   English   中英

為什么函數給了我錯誤的數字?

[英]why function gives me back wrong number?

在程序中編寫並測試自己的函數:

  1. int function1 (const char * string1, const char * string2)字典順序比較兩個字符串,如果字符串相同則返回 0,如果 string1 早於 string2,則返回 -1,如果 string1 晚則返回 +1,例如function1 ("cca" , "abcd") -> 1 , function1 ("abcde", "b") -> -1
  2. int function2 (const char * string)返回出現在字符串中的唯一數字的數量,例如function2 ("ab512af6kc1") -> 3

     int main() { cout << cmp("abc","a") << endl; } int cmp(const char* string1, const char* string2) { for(int i = 0; i < len(string1); i++) { if (i == len(string1)) { return 0; } else if (string1 > string2) { return 1; } else if (string1 < string2) { return -1; } } }

它返回我 -1 但應該返回 1 因為“abc”在字典中比“a”晚。

第二個練習呢? 我不知道如何開始。

正如我在評論中發布的那樣,你應該回去重新閱讀你的 C++ 書。 string1string2是指針,你不應該在這里比較它們。

這是問題 1 的有效解決方案:

#include <cstring>
#include <iostream>

int cmp(const char* string1, const char* string2) {
    int n1 = std::strlen(string1);
    int n2 = std::strlen(string2);
    int i=0;
    while (i<n1 && i<n2)
    {
        if (string1[i] < string2[i]) return -1;
        else if (string1[i] > string2[i]) return 1;
        else i++;
    }
    if (n1 == n2) return 0;
    if (i == n1) return -1;
    return 1;
}

int main()
{
    std::cout << cmp("a","abc") << std::endl;
    return 0;
}

對於第二個問題,您可以通過使用哈希圖保持字符數來解決。

兩個練習的實時樣本

對於練習 1 ,我相信目標是創建一個類似於strcmp()的函數,所以重要的不是大小而是字典順序,所以你應該做的是比較每個字符,例如cmp("abcd", "abce")應該是-1並且cmp("abce", "abcd")cmp("abe", "ab")應該是1

int cmp(const char* string1, const char* string2) {

    do{
       if(*string1 > *string2){  //because of ASCII codes you can compare characters like this
           return 1;
       }
       if(*string1 < *string2){
           return -1;
       }      
    } while(*string1++ && *string2++); //while none of the chars is null

    return 0;  //reached if no different chars were found so the strings are equal
}

對於練習 2,您可以將數字提取到不同的容器中,對它們進行排序和比較:

int function2 (const char * str){

    vector<int> digits; //dynamic container since the digit count is unknown at first
    int count = 0;

    for(size_t i = 0; i < strlen(str); i++)  //extract digits from string
        if(str[i] >= '0' && str[i] <= '9')
             digits.push_back(str[i] - '0'); //add to digit container

    sort(digits.begin(), digits.end()); //sort digit vector

    for(size_t i = 0; i < digits.size() - 1; i++){ //compare digits and count if no repeat
        if(digits[i] != digits[i + 1] && digits[i + 1] != digits[i + 2]){
            count++;
        }
    }
    return count;
}

圖書館

#include <cstring>
#include <vector>
#include <algorithm>

暫無
暫無

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

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