我被赋予了在c++中编写代码的任务,我必须开发一个算法来检查以下条件中的3个数字,如果第一个数字指数第二个数等于第三个数字,那么它应该返回真假。我使用幂函数来查找第一个数字被提升到第二个数字,而另一个称为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;
}发布于 2020-06-12 14:41:21
您可以接受要执行输出的函数中的输出流,如下所示:
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发布于 2020-06-12 14:43:34
我得到了一个错误,它说没有声明出文件,
因为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;
}https://stackoverflow.com/questions/62346521
复制相似问题