我被交给一个用C++编写的任务,我必须开发一个算法,在以下条件下检查3个数字,如果第一个数字的指数第二个数字等于第三个数字,那么它应该返回真或假。 我使用幂函数找到第一个数字上升到第二个数字和另一个函数称为comapare(num1,num2,num3)。我的程序工作良好,但问题是它在一个控制台显示结果,我想输出到一个我命名为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
我得到一个错误,它说未声明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;
}