对于语句递增/递减错误
For statment increment/decrement error
我是使用C++的新手。我读过书,一直在使用互联网。在这里 - 练习 16 - https://en.wikibooks.org/wiki/C%2B%2B_Programming/Exercises/Iterations#EXERCISE_16(
我不明白为什么我的"for"陈述不起作用,当它似乎符合标准时。完整的代码如下,我将指出对我不起作用的位:
#include <iostream>
using namespace std;
void primecheck(int z)
{
bool primes = true;
// start at 1 because anything divisible by zero is an error
for (int i=1; i<=z; i++)
{
if (z%i == 0)
{
// ignore if divisible by 1 or itself do nothing
if ( i == z || i == 1)
{}
// if it can be divided by anything else it is not a prime
else
{
primes = false;
//break;
}
}
}
(primes == true) ? (cout << z << " is a prime number" << endl) : (cout << z << endl);
}
int main()
{
int x;
cout << "Enter a number to see if it is a prime number" << endl;
cin >> x;
for (x; x>0; x--)
{
primecheck(x);
}
}
工作代码如上,但最初我有:
for (x; x<=1; x--)
{
primecheck(x);
}
对我来说,这更有意义,因为我输入了一个高值,例如 5,并且我希望它减少到每个循环直到它为 1。但是每当我这样做时,它只是跳过了整个陈述。为什么会这样?
你需要这个:
for (; x>=1; x--)
{
primecheck(x);
}
你之前说过的继续这个 for 循环,只要 x 是 <= 1。但是您的初始输入将大于 1(假设,因为您正在检查素数(,因此循环永远不会运行。换句话说,如果你输入任何大于1的数字(比如10(,它将检查条件10<=1。这将计算为 false,循环将终止
for (x; x<=1; x--)
{
primecheck(x);
}
等效于以下while
循环:
x;
while (x<=1)
{
primecheck(x);
x--;
}
那是:
-
x;
毫无意义,因为它什么都不做。 for
循环中间部分的条件不是停止条件。只要为真,循环就会运行。当您输入一个高值(如5
(时,x<=1
从一开始就为 false,因此循环永远不会运行。条件必须为 true 才能运行。
相关文章:
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 语句错误:"","标记之前有"预期的')'
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 为什么切换 if else 语句的顺序会导致错误?
- 错误:调用 .. at return 语句时没有匹配函数
- 为什么 if 语句在 Java 中"if(1)"给出错误,但在C++中成立?
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 错误:中断语句不在循环或交换机内
- 错误:void 值未被忽略,因为它应该被忽略,错误:返回语句具有值
- 循环包含导致链接错误的语句
- 带有值的递归阶乘错误返回语句,在函数中返回 'void' [-fallowive]
- C++断言导致段错误的语句
- 如何设置错误处理语句的格式
- 错误:break语句不在循环中,而实际上它在循环中
- 包括导致预期函数体错误的语句