簡體   English   中英

在此作用域錯誤中未聲明c ++ to_string [Windows + Devcpp環境]

[英]c++ to_string was not declared in this scope error [Windows + Devcpp environment]

我正在嘗試使用Devcpp ide在Windows 10上的c ++中實現Karatsuba乘法算法。 這是相同的代碼:

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int karatsuba(int x, int y){
    string sx = to_string(x);
    string sy = to_string(y);
    int len_x = strlen(sx);
    int len_y = strlen(sy);
    if (len_x == 1 && len_y == 1)
        return x * y;
    else{
        int n = max(len_x, len_y);
        int n_by_2 = n / 2;

        int a = x / pow(10, n_by_2);
        int b = x % pow(10, n_by_2);
        int c = y / pow(10, n_by_2);
        int d = y % pow(10, n_by_2);

        int ac = karatsuba(a, c);
        int bd = karatsuba(b, d);

        int ad_plus_bc = karatsuba(a+b, c+d);
        int prod = ac * pow(10, n_by_2) + (ad_plus_bc * pow(10, n_by_2)) + bd;
        return prod;
    }
}

int main(){
    cout<<karatsuba(45, 45);
}

當我運行該程序時,出現以下錯誤:

C:\\ Users \\ AKuro \\ Desktop \\ C ++ \\ Divide and Conquer \\ karatsuba.cpp在函數'int karatsuba(int,int)'中:7 25 C:\\ Users \\ AKuro \\ Desktop \\ C ++ \\ Divide and Conquer \\ karatsuba.cpp [錯誤]未在此范圍內聲明“ to_string”

9 23 C:\\ Users \\ AKuro \\ Desktop \\ C ++ \\ Divide and Conquer \\ karatsuba.cpp [錯誤]在此范圍內未聲明“ strlen”

18 29 C:\\ Users \\ AKuro \\ Desktop \\ C ++ \\ Divide and Conquer \\ karatsuba.cpp [錯誤]類型為'int'和'__gnu_cxx :: __ promote_2 :: __ type {aka double}'的無效操作數到二進制'operator%'

20 29 C:\\ Users \\ AKuro \\ Desktop \\ C ++ \\ Divide and Conquer \\ karatsuba.cpp [錯誤]類型為'int'和'__gnu_cxx :: __ promote_2 :: __ type {aka double}'的無效操作數對二進制'operator%'

我嘗試了通過谷歌搜索找到的方法,但似乎沒有一個起作用。 這是我已經嘗試過的:

將std與to_string一起使用,例如std :: to_string

我什至嘗試過這種方法

int i = 1212;
stringstream ss;
ss << i;
string s=ss.str();

但似乎都無法正常工作,而且我找不到針對此特定環境(Windows 10 + Devcpp)的任何答案。 這真的讓我煩惱。 請您幫我一下。

這里有多個錯誤:

1) to_string()c ++ 11的功能 因此,請確保在makefile或IDE中設置-std = c ++ 11。

2) strlen()是在cstring聲明的,而不是在string聲明的。 更好的方法是使用類似int len_x = sx.size(); ,其他字符串相似。

3) pow() )的返回類型為float或double 因此,您需要像這樣顯式地轉換它: int b = x % static_cast<int>(pow(10, n_by_2)); 您需要對所有使用pow()並將表達式分配給int變量的表達式執行此操作。 實際上,編寫自己的簡單intpow()函數要比強制轉換更好,這並不難做到(它是如此簡單,以至於該標准似乎已經跳過了它:-))。

暫無
暫無

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

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