我被赋予了用c ++编写代码的任务,我不得不开发一种算法,可以按照以下标准检查3个数字,如果firts指数第二个数字等于第三个数字,那么我应该返回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;
}
答案 0 :(得分:1)
您可以在想要执行输出的函数中接受输出流,如下所示:
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
答案 1 :(得分:0)
我收到一条错误消息,指出未声明outfile,
因为outfile
是在main()
之外使用的
您犯了语法错误。取下支架
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
} // <- main() ends here
infile.close();
outfile.close();
return 0;
}