如何在递归中仅使用最终值?

How to use only the final values in recursion?

本文关键字:递归      更新时间:2023-10-16

我正在开发一个将 z3 表达式转换为 qdimcas 格式的程序。 下面的代码将 qdimacs 格式代码打印到文件中。

在这里,每次调用函数时clause_count修改变量。 有没有办法只能使用或只打印clause_count的最终值?

#include<iostream>
#include "z3++.h"
#include<string>
#include<fstream>
using namespace z3;
using namespace std;

int dimacs(int t, string oprt, int arg_num,int element[],int variables)
{   int static clause_count = 0;
int static check =0;
std::cout<<"Value of T is: "<<t<<" operator is: "<<oprt<<" Nuumber of arguments: "<<arg_num<<endl;
if(arg_num==2)
std::cout<<element[0]<<" "<<element[1]<<endl;
else
std::cout<<element[0]<<endl;        
ofstream myfile;
myfile.open("contents.txt",ios::app);
myfile.clear();
if(check == 0)
{ 
myfile<<"p cnf n";
check++;
}
if(arg_num == 2)
{   clause_count+=3;
if(oprt.compare("and")==0)
{
myfile<<"-"<<t<<" "<<element[0]<<" 0 n";
myfile<<"-"<<t<<" "<<element[1]<<" 0 n";
myfile<<"-"<<element[0]<<" -"<<element[1]<<" "<<t<<" 0 n";
myfile.close();
std::cout<<"printing done for AND.n";
}
else if(oprt.compare("or")==0)
{
myfile<<t<<" -"<<element[0]<<" 0 n";
myfile<<t<<" -"<<element[1]<<" 0 n";
myfile<<"-"<<t<<" "<<element[0]<<" "<<element[1]<<" 0 n";
myfile.close();
std::cout<<"printing done for OR.n";
}
else if(oprt.compare("=>")==0)
{
myfile<<"-"<<t<<" -"<<element[0]<<" 0 n";
myfile<<"-"<<t<<" "<<element[1]<<" 0n";
myfile<<"-"<<element[1]<<" -"<<t<<" "<<element[0]<<" 0 n";
myfile.close();
std::cout<<"printing done for implies.n";
}
}  
else if(arg_num == 1)
{   clause_count+=2;
if(oprt.compare("not")==0)
{
myfile<<"-"<<t<<" -"<<element[0]<<" 0n";
myfile<<t<<" "<<element[0]<<" 0 n";
myfile.close();
std::cout<<"printing done for NOT.n";
}
}  
std::cout<<clause_count<<endl;
std::cout<<variables<<endl;
}

我基本上只需要存储clause_count的最终值并将其传递给另一个函数。

实际上还有另一个文件调用此函数,并且该文件运行递归。在递归调用中,调用此 dimacs 函数并通过它传递参数。 最后,每当调用此函数时,dimacs 文件都会打印输出,输出应该是这样的:

p cnf 3 4
1 2 0
2 1 0 
2 4 0
4 5 0

这里用"P CNF"行有 2 个值,即 3 和 4,其中 4 必须存储在我的程序的变量clause_count中。但是由于递归,我打印了clause_count的每个值。我只需要最终值。

由于您使用的是静态变量(基本上是仅在 dimacs 中可见的全局变量),我建议移动 静态clause_count声明到函数外部的全局变量声明。