我接到一个任务,用C++编写代码,我必须开发一个算法,检查3个数字在以下标准,如果第一数字指数第二数字等于第三数字,那么它应该返回真或假。我利用power函数找到第一个数字上升到第二个数字,另一个函数叫做comapare(num1,num2,num3).My 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
我得到一个错误,说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;
}