2016-03-26 20 views
-1

C++で数値をバイナリに変換する関数を作成しようとしていますが、関数を呼び出すときに空の文字列を返します。空文字列を返す文字列関数C++

はここに私のコードです:私はreturn文の前にcout << out << endl;を含む行を追加する場合

#include <iostream> 
#include <stdio.h> 
#include <vector> 
#include <string.h> 
#include <math.h> 
#include <algorithm> 

using namespace std; 

string dec2bin(long long x, vector<long long> extra = { }) { 

    string out; 
    string output; 
    int i = 0; 
    long long sum = 0; 
    bool ok = false; 

    if(!extra.empty()) { 
     for(int a = 0; a < extra.end() - extra.begin(); a++) { 
      sum += pow(2, extra[a]); 
     } 
    } 

    while(pow(2, i) + sum < x) { 
     i++; 
    } 
    if(i > 0) { 
     i--; 
    } 
    extra.push_back(i); 

    if(pow(2, i) + sum == x) { 

     long long max = *max_element(extra.begin(), extra.end()); 

     for(int a = max; a >= 0; a--) { 
      if(std::find(extra.begin(), extra.end(), a) < extra.end()) { 
       out += '1'; 
      } 
      else { 
       out += '0'; 
      } 
     } 
     ok = true; 
    } 

    if(ok) { 
     return out; 
    } 
    else { 
     dec2bin(x, extra); 
    } 
} 

int main() { 

    long long a; 
    cin >> a; 

    cout << dec2bin(a) << endl; 

    return 0; 

} 

、それは文字列を出力します。すべてのヘルプははるかに高く評価される:)

+0

あなたは 'pow'を使うべきではありません。 'pow'は二重を返すので、あなたは潜在的に数字を失います。潜在的に' long long'に 'double'を格納しています。コンパイラの警告レベルを上げます。 – PaulMcKenzie

+0

また、整数使用に 'pow'を使うことについてはこちらを参照してください:http://stackoverflow.com/questions/25678481/why-pown-2-return-24-when-n-5 – PaulMcKenzie

答えて

0

に他の変更dec2bin(x, extra);の下で:

return dec2bin(x, extra); 

は、私はそれがあなたの問題だと思います。

関連する問題