接受整数输入并返回字符串的函数

时间:2019-11-04 19:09:13

标签: c++

我想创建一个函数,该函数接受用户给定的整数并返回一个字符串,该字符串声明所提供的整数是整数还是素数。

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

test_prime(int n){
    string result;
    if(n % 2 == 0||n % 3 == 0 || n % 5 == 0 || n % 7 == 0){
        string s("Composite");
        result = s;
    }
    else{
        string s("Prime");
        result = s;
    }
    return(result);
}


int main(){
    int n;
    string result;
    cout << "Please type any integer";

    cin >> n;

    test_prime(n);

    cout << result;

    return(0);
}

我收到与返回变量“结果”有关的以下错误:“无法将'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string}'转换为return int中的'int'” / p>

2 个答案:

答案 0 :(得分:1)

您的代码有几个问题:

  1. 您忘记指定test_prime的返回类型。如果不这样做,它将默认为int。这就是错误消息指示的内容:"cannot convert 'std::string' to 'int' in return"。它需要一个int,但是您正在尝试返回一个string
  2. 您没有将test_prime的返回值分配给result。您最终将空的result字符串打印到输出中。
  3. test_prime函数不正确(例如,它返回5的“ Composite”)。我还没有修改,只是编程错误。

corrent程序(将其清理了一下):

#include <iostream>
#include <string>

using namespace std;

string test_prime(int n) {
    if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0 || n % 7 == 0) {
        return "Composite";
    }
    return "Prime";
}


int main() {
    cout << "Please type any integer: ";
    int n;
    cin >> n;
    cout << test_prime(n);

    return 0;
}

答案 1 :(得分:0)

这是有效的更新代码。

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

std::string test_prime(int n){
    string result;
    if(n % 2 == 0||n % 3 == 0 || n % 5 == 0 || n % 7 == 0 || n == 0){
        string s("Composite");
        result = s;
    }
    else{
        string s("Prime");
        result = s;
    }
    return(result);
}


int main(){
    int n;
    string result;
    cout << "Please type any integer ";

    cin >> n;

    cout << test_prime(n);

    return(0);
}