Home > OS >  Why doesn't cout work in my code and doesn't show (i - 1) to me?
Why doesn't cout work in my code and doesn't show (i - 1) to me?

Time:12-12

Can anyone help me with this code?I don't know why cout doesn't work and it doesn't show the (i - 1) in line 14;

The question is: Joe have 240 minute to do his exam.First question need 5 minute time,second question want 10 minute and etc.He need k minutes to eat dinner after exam.Now we want to know how many questions can he do. n is number of questions and k is the time that takes for eating dinner.

 #include <iostream>

using namespace std;

int main()
{
    int i, n, k, sum = 0;
    cin >> n >> k;
    for(i = 1; i <= n; i  ){
        if(sum <= 240 - k){
            sum  = 5 * i;
        }
        else{
            cout << i - 1;
            break;
        }
    }
}

CodePudding user response:

cout is buffered. i probably does appear, just not where you're looking: right before the next prompt, because you're not sending a newline.

cout << i - 1 << '\n';

You may also see:

cout << i - 1 << endl;

Here, endl is a newline plus an instruction. When inserted into the ostream, if causes a flush, forcing all pending output to be written. That can be handy when you need to interleave buffers on one device, as when sending standard input and standard output to the same file or terminal.

CodePudding user response:

because there is case like for n = 5 and k = 10 where sum cannot reach the threshold to actually print. i'm not sure about what you want to do but printing out of the loop might help.

#include <iostream>

using namespace std;

int main()
{
    int i, n, k, sum = 0;
    cin >> n >> k;
    for(i = 1; i <= n; i  ){
        if(sum <= 240 - k){
            sum  = 5 * i;
        }
        else{
            break;
        }
    }
    cout << i - 1;
}
  •  Tags:  
  • c
  • Related