一个数字和字符串相互转换的实用方法

数字转字符串

string rrstring(int value) {
    std::ostringstream cout;
    cout << value;
    string str = cout.str();
    return str;
}

字符串转数字

int numbers(string s) {
    int res;
    std::stringstream cout;
    cout << s;
    cout >> res;
    return res;
}

案例

#include
using namespace std;
int judge(int n) {
    double sum = 0;
    for (int i = 1; i <= n / 2; i++) {
        if (n % i == 0) {
            sum += i;
        }
    }
    if (sum == n)return 1;
    else return 0;
}

string rrstring(int value) {
    std::ostringstream cout;
    cout << value;
    string str = cout.str();
    return str;
}
int numbers(string s) {
    int res;
    std::stringstream cout;
    cout << s;
    cout >> res;
    return res;
}
string prin(int n) {
    string s = "";
    for (int i = 1; i <= n / 2; i++) {
        if (i == n / 2) {
            if (n % i == 0) {
                s += rrstring(i);
            }
        }
        else {
            if (n % i == 0) {
                s += rrstring(i) + ",";
            }
        }
    }
    return s;
}

int main() {
    for (int i = 1; i <= 1000; i++) {
        if (judge(i) == 1) {
            cout << i << " its factors are ";
            cout << prin(i) << endl;
        }
    }
    return 0;

}

你可能感兴趣的:(ACM_Training,c++,算法,开发语言)