如何在递归中仅使用最终值?
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声明到函数外部的全局变量声明。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败