You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows+Dev-C++环境下to_string未在此作用域声明错误求助

Fixing "to_string was not declared in this scope" in Dev-C++ for Karatsuba Multiplication

Hey there! Let's tackle that error you're seeing head-on. The core issue here is that Dev-C++ defaults to an older C++ standard (like C++98), but std::to_string was only introduced in C++11. Here's how to fix this and polish up your code along the way:

Step 1: Enable C11 (or Newer) in Dev-C

  1. Open Dev-C++ and navigate to Tools > Compiler Options.
  2. In the "Add the following commands to the compiler command line" input box, add: -std=c++11 (you can also use -std=c++17 if you want access to newer C++ features).
  3. Click OK to save the setting. This tells the compiler to use the C++11 standard, which includes std::to_string.

Step 2: Fix Other Potential Bugs in Your Code

Your current code has a couple of small issues that could cause unexpected behavior later:

  • You're using strlen() on a std::string—use sx.size() or sx.length() instead (these are the proper methods for C++ string objects).
  • pow() returns a double, which can lead to precision errors when casting to int (e.g., pow(10,2) might return 99.9999999 instead of 100.0, becoming 99 after casting). We'll replace this with integer-based power calculation to avoid that.

Here's a corrected, complete version of your Karatsuba code:

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm> // For std::max

using namespace std;

int karatsuba(int x, int y) {
    string sx = to_string(x);
    string sy = to_string(y);
    int len_x = sx.size();
    int len_y = sy.size();

    // Base case: single-digit multiplication
    if (len_x == 1 && len_y == 1) {
        return x * y;
    }

    int n = max(len_x, len_y);
    int n_by_2 = n / 2;

    // Calculate 10^n_by_2 with integer precision (avoids double errors)
    int power_of_10 = 1;
    for (int i = 0; i < n_by_2; ++i) {
        power_of_10 *= 10;
    }

    int a = x / power_of_10;
    int b = x % power_of_10;
    int c = y / power_of_10;
    int d = y % power_of_10;

    // Karatsuba's core steps
    int ac = karatsuba(a, c);
    int bd = karatsuba(b, d);
    int ad_bc = karatsuba(a + b, c + d) - ac - bd;

    return ac * static_cast<int>(pow(10, 2 * n_by_2)) + ad_bc * power_of_10 + bd;
}

int main() {
    int x, y;
    cout << "Enter two integers: ";
    cin >> x >> y;
    cout << "Result: " << karatsuba(x, y) << endl;
    return 0;
}

Quick Notes:

  • After updating the compiler settings, make sure to clean your build first (Build > Clean) before recompiling to apply the changes.
  • The integer-based power calculation eliminates the precision risks of using pow() for small exponents.

内容的提问来源于stack exchange,提问作者AKuro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:23:47