如果语句c 错误,请打破
Break if statement c++ error
我正在编写线性和二次探测哈希表程序。
这是我用于线性探测功能的循环,它的工作原理很好。
//when there's a collision increase i by 1 until finding empty slot
for(i = (hashVal % tableSize+1) % tableSize; i <tableSize; i++)
if(a[i] == -1){
a[i] = hashVal;
break;
}
所以我在二次探测功能中再次写了一个for循环以处理Collision
//when there's a collision increase i by i^2
j = 0;
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
j = i^2;
if(a[j] == -1){
a[j] = hashVal;
break;
}
但是当我编译二次探测时,我会收到此错误
error: 'break' statement not in loop or switch statement
我真的很困惑,为什么它在线性探测中良好时会导致第二个错误。谁能解释为什么?
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
j = i^2;
这是您的周期,因为您没有将卷曲括号围绕在上面。
修复很简单,放置那些牙套:
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
{
j = i^2;
if(a[j] == -1){
a[j] = hashVal;
break;
}
}
经验法则 - 当您使用循环或静态时,请始终放置卷曲牙套,因为它可以帮助您不犯此类错误。
,因为只有下面的语句是for循环主体,所以
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
j = i^2; // the body of for loop
// not for loop body from here (note the correct indent position)
if(a[j] == -1){
a[j] = hashVal;
break;
}
对于您的第一个代码示例,整个if
语句是用于循环主体,因此可以正常工作。
要修复代码,您可以使用牙套使其成为复合语句,该语句可能由多个语句组成。
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
j = i^2;
if(a[j] == -1){
a[j] = hashVal;
break;
}
}
您没有在for
语句的主体周围放牙套。这在第一个示例中起作用,因为主体只是if
语句,但是在您的第二个示例中,仅将j = i^2;
解析为for
的一部分。该代码等效于:
//when there's a collision increase i by i^2
j = 0;
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
j = i^2;
}
if(a[j] == -1){
a[j] = hashVal;
break;
}
您可以通过在正确的位置添加牙套来解决此问题:
//when there's a collision increase i by i^2
j = 0;
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
j = i^2;
if(a[j] == -1){
a[j] = hashVal;
break;
}
}
一个好的经验法则是将牙套放在任何循环主体周围,该循环主体不超过一条线长。许多人会建议您在以后的时间内添加更多的循环主体,甚至在单行周围放牙套。
相关文章:
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 语句错误:"","标记之前有"预期的')'
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 为什么切换 if else 语句的顺序会导致错误?
- 错误:调用 .. at return 语句时没有匹配函数
- 为什么 if 语句在 Java 中"if(1)"给出错误,但在C++中成立?
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 表单显示对话框函数错误,并且不执行下面的语句
- 我收到一个断言错误,但是当我编写 cout 语句时,它会消失
- 我可以使用 try catch 语句来捕获任何错误而不是具体错误吗?
- 我在c++中遇到了一个奇怪的错误,其中一个计算2个小整数加法的语句溢出到一个长值中
- Qt SQL LIKE语句返回错误
- 错误:语句无法解析重载函数C++的地址
- 当我通过删除临时节点来释放内存时,我会得到读取访问违规行为.但是只有当我返回错误语句时
- C++显示错误的 constexpr 错误语句
- C++错误:语句无法解析重载函数的地址
- C++:在CodeBlocks上编译和运行的程序可以工作,但从终端它给出错误语句