![](/img/trans.png)
[英]function which takes a string as input and returns the most frequent character
[英]Function that takes integer inputs and returns a string
我想創建一個 function 接受給定 integer 的用戶並返回一個字符串,該字符串聲明提供的 integer 是合數還是素數。
#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);
}
我收到以下與返回變量“result”相關的錯誤:“無法將 'std::__cxx11::string {aka std::__cxx11::basic_string}' 轉換為 'int' in return|”
您的代碼有幾個問題:
test_prime
的返回類型。 如果您不這樣做,它將默認為int
。 這就是錯誤消息所指示的內容: "cannot convert 'std::string' to 'int' in return"
。 它需要一個int
,但您正試圖返回一個string
。test_prime
的返回值分配給result
。 您最終會將空result
字符串打印到 output。test_prime
function 不正確(例如,它返回 5 的“復合”)。 我沒有修改,只是編程錯誤。正確的程序(清理了一點):
#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;
}
這是有效的更新代碼。
#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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.