简体   繁体   English

C++ cout 不能在里面工作,如果?

[英]C++ cout won't work inside for and if?

I have those two pieces of code as my home assignment.我有这两段代码作为我的家庭作业。 The code looks all fine to me, but it won't print out what I want, no matter what.代码对我来说看起来很好,但无论如何它都不会打印出我想要的东西。 In fact, the console output remains completely empty.事实上,控制台输出仍然完全是空的。

The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a :第一个程序应该打印出满足ladna()函数要求并且在1a之间的所有数字:

#include <iostream>

using namespace std;

int a;
int i = 1;

bool ladna(int a)
    {
    if((((a>>4)*5+a*2)%3)==1)
        return true;
    else
        return false;
    }

int main()
{

    cerr << "Podaj liczbe: " << endl;
    cin >> a;

    while (i <= a){

        if (ladna(a)){
            cout << i << " ";
        }

        i++;

    }

}

the ladna() function is premade and I have to use it as is. ladna()函数是预制的,我必须按原样使用它。

I tried changing while into do...while and for , didn't help.我尝试将while更改为do...whilefor ,但没有帮助。 Doesn;t work with cerr either.也不适用于cerr

The second code has to print out all the natural divisors of number a .第二个代码必须打印出数字a所有自然除数。

#include <iostream>

using namespace std;

int main()
{

    int a;

    cerr << "Podaj liczbe" << endl;
    cin >> a;

    for (int i = 0; i >= a; i++){

        if (a % i == 0){

            cout << i << endl;
        }

    }

    return 0;
}

Doesn't work either.也不行。

To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same.在我看来,这两段代码似乎都有相同的问题,因为它们的编写方式相同,基于相同的原理,并且错误相同。 Hence my assumption, that the cause is the same as well.因此我的假设,原因也是一样的。

Unfortunately, for the love of me, I simply can't see what said error is...不幸的是,为了我的爱,我根本看不出所说的错误是什么......

For the first code:对于第一个代码:

I think you should call ladna function with i, like ladna(i)我认为你应该用 i 调用 ladna 函数,比如ladna(i)

For the second code:对于第二个代码:

In for it should be i<=a for它应该是i<=a

'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. '%' 是模运算符,在(a%i)的执行过程中,您将 a 与 i 相除并取余数,因为我从零开始,由于被零除,您将得到“浮点异常(核心转储)”。 So, for should start with 1. This should work:所以, for应该从 1 开始。这应该有效:

for (int i = 1; i <= a; i++){

    if (a%i == 0){

        cout << i << endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM