简体   繁体   中英

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 :

#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.

I tried changing while into do...while and for , didn't help. Doesn;t work with cerr either.

The second code has to print out all the natural divisors of number 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)

For the second code:

In for it should be 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. So, for should start with 1. This should work:

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

    if (a%i == 0){

        cout << i << endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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