我的程序正在将错误的数据写入我的输出文件,而且我不确定为什么会发生这种情况。我实质上是通过确定是否缺少任何括号或括号来检查方程是否平衡。这些方程式正在从输入文件中读取。为了检查它们是否平衡,我正在使用堆栈。无论出于何种原因,我的程序要么过多地计算了缺少的字符数量,要么甚至没有意识到缺少字符。
从我尝试做的测试来看,似乎我的程序可能在某些地方循环了更多的时间。但是,我不确定。我还尝试用较小的输入大小测试程序,但这没用。
这是相关的代码。应该注意的是,这是针对我不使用STL模板的挑战。我的堆栈功能基本上以相同的方式工作。我的pop函数删除堆栈顶部的所有内容,并将其复制到字符变量
//create stack
DynStack mystack;
//pushes elements to stack
for (int i=0; i<size; i++) {
if (array[i] == '(' || array[i] == '[') {
mystack.push( array[i] );
continue;
}
// Stack will remain empty until an
// an open character is reached.
// While empty, opening characters are missing
if ( mystack.isEmpty() ) {
if (array[i] == ')') {
closedP++;
}
else if ( array[i] == ']' )
;
ClosedB++;
}
//compares stack to elements in array.
// if the do not match, then an element is missing.
if (array[i] == ')') {
mystack.pop(c);
if ( c == '[' ) {
openP++;
}
}
if ( array[i] == ']' ) {
mystack.pop(c);
if (c == '(') {
OpenB++;
}
}
}
//if there is still an element left in the stack
//after checking the entire expression, it is either
//missing a ')' or a ']'
if (!mystack.isEmpty()) {
mystack.pop(c);
if (c == '(') {
closedP++;
}
else if (c == '[')
ClosedB++;
}
// cout<<"OP: "<<openP<<endl<<"CP: "<<closedP<<endl<<
// "OpenB "<<OpenB<<endl<<"CB: "<<ClosedB<<endl;
// cout<<"total: "<<totalmissing<<endl;
totalmissing=openP+closedP+OpenB+ClosedB;
//prints valid expression
if (totalmissing == 0) {
outfile<<math<<" "<< "=== "
<<"valid expression"<<endl;
}
//prints the amount of each element missing to output file
//if the number of missing elements is less than 6
if ( totalmissing >= 1 && totalmissing < 6 ) {
outfile<<math<<" "<< "=== "<<"missing "
<<"("<<openP<<") "<<"('s"<<" and "<<"("<<closedP<<") "<<")'s"
<<" and "<<"("<<OpenB<<") "<<"['s"<<" and "<<"("<<ClosedB
<<") "<<"]'s"<<endl;
}
// expression is missing 6 or more elements
if (totalmissing >= 6 || OpenB >=6
|| ClosedB>=6 ||openP >=6 || closedP >=6 ) {
outfile<<math<<" "<<"6 or more elements are missing"<<endl;
}
输入以下内容:
a+(b/c)*abcd(efgh
(60+[efg]+[efm)
70+1]
)aphids(
]dkdjsfg-4tw[abds()
我应该告诉用户该表达式是否有效,如果无效,请告知缺少的内容。如果失踪人数超过6,我应该告诉他们。
根据您所提供的内容,您将会看到,我提供的表达式有问题的输出是不正确的。
a+(b/c)*abcd(efgh 6 or more elements are missing
(60+[efg]+[efm) === missing (1) ('s and (1) )'s and (0) ['s and (0) ]'s
70+1] 6 or more elements are missing
)aphids( 6 or more elements are missing
]dkdjsfg-4tw[abds() 6 or more elements are missing
任何帮助将不胜感激!
答案 0 :(得分:0)
正确的缩进对于阅读代码很重要。这部分看起来很可疑:
if ( mystack.isEmpty() ) {
if (array[i] == ')') {
closedP++;
}
else if ( array[i] == ']' )
;
ClosedB++;
}
实际上是:
if ( mystack.isEmpty() ) {
if (array[i] == ')') {
closedP++;
}
else if ( array[i] == ']' )
; // noop here
ClosedB++; // always executed (if stack is empty)because outside of inner if block
}
为避免此类错误,我强烈建议您对if块保持一致:除非唯一的声明与{}
(或{在同一行),否则始终使用大括号(if
) {1}}或else if
)是。
这足以解释您的错误结果,但是由于您没有提供最小,完整和可验证的示例,因此我无法测试对其进行修复是否足以提供预期的输出。