我被赋予了用c++编写代码的任务,我不得不开发一种算法,按照以下标准检查3个数字,如果第一个指数的第二个数字等于第三个数字,那么我应该返回true或false。我使用幂函数来查找第一个数字升为第二个数字,以及另一个称为comapare(num1,num2,num3)的函数。我的pogramme正常工作,但问题是它在控制台中显示了结果,我想输出到输出我将文件命名为outfile的文件,当我这样做时,我收到一条错误消息,指出未声明outfile,我将不胜感激,能够将其输出到输出文件。
下面是我的代码
#include <iostream>
#include<fstream>
using namespace std;
double powerfunc(double num1,double num2){ // power function
double base=num1,exponent=num2,result;//decalsring base and exponent
for(int i=1;i<exponent;i++){
base=base*base;
result=base;
}
return result;
}
double compare(double x, double y,double z){//Comapares if x exponent y gives z and return
//Return true or false
int storersults;
if( (powerfunc(x,y)== z)){
cout<<"true"<<endl;
//outfile<<"true"<<endl;
storersults=powerfunc(x,y);
cout<<"results is "<<storersults;
//outfile<<"results is "<<storersults;
}
else{
cout<<"false"<<endl;
//outfile<<"false"<<endl;
storersults=powerfunc(x,y);
cout<< " results is "<<storersults;
//outfile<<"results is "<<storersults;
}
return storersults;
}
int main(){
ifstream infile;
ofstream outfile;
infile.open(" input.txt");
outfile.open("output.txt");// I wanna link output to functions above and get results // I wann get results on outputfile not on console
// double a,b,c;
//infile>>a,b,c;
powerfunc(3,2);//This functions finds power of 3 and 2
compare(3,2,9);//This fucnions compare if 3^2=9 then retuens true
}
infile.close();
outfile.close();
return 0;
}
最佳答案
您可以在想要执行输出的函数中接受输出流,如下所示:
double compare(double x, double y,double z, std::ostream &out) {
// ^^^ accept some stream
out << "hello"; // print whatever output to the stream
}
然后在
main
中,您可以这样调用它:outfile.open("output.txt");
compare(3,2,9, std::cout); // to print to console
compare(3,2,9, outfile); // to print to file
关于c++ - 处理输入和输出的C++函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62346521/