Как пошагово работает код C ++ с двумя целыми числами? - PullRequest
1 голос
/ 07 мая 2020

Я новичок в программировании на C ++, я уже рассматривал циклы while в python раньше, однако здесь меня смущают два целых числа. Я был бы очень рад, если бы вы объяснили мне, как это работает при l oop шаг за шагом.

#include<iostream>
using namespace std;
int main() {
    int i;
    int j; 
    while(i<10 || j < 5) { // i kucuk ondan kucuk oldu surece {} icerisindeki islemler surekli olarak while() loopu ile tekrarlancak 
        cout<<"i: "<<i<<" "<<"j: "<<j<<endl;
        i = i + 1;  // eger bu kod olmaz ise, sonsuza dek i degerine basacak
        j = j + 1;
    }
    return 0;
}

Ответы [ 2 ]

2 голосов
/ 08 мая 2020
#include<iostream>
using namespace std;
int main() {
/* You should first give a starting value
 to the I and j, otherwise they 
 will get a random number and your while won't work*/ 
    int i=0; 
    int j=0;
/* so as the word says "while" - while (something here is true)do the 
following code between the starting 
brackets and the finishing brackets. When it's not True skip the loop and go to the next line, in this example we will go to return 0 */ 

/*The value of i is 0 and the value of j is 0, and we first check if 0(i)<10 that's true next we check the other one 
if 0(j) < 5 yes do the following block*/
/* the || mean "or' if either one of them 
is true do the following block of code between the brackets*/

    while(i<10 || j < 5) {
        //we print
        cout<<"i: "<<i<<" "<<"j: "<<j<<endl;
        //we are incrementing the values of i and j for 1;
        i = i + 1;  
        j = j + 1;

        /*so what happens now it jumps again to the while
          and checks if the statement is true, now i = 1 and j = 1; 
          and this runs until i is 10 because only then the i won't be lesser then 
          10 and j won't be lesser then 5 it will be false*/ 
       */

    }
    //close the program
    return 0;
}

Надеюсь, я все прояснил!

0 голосов
/ 08 мая 2020

Вы не объявляете переменные в Python. «Переменная» создается, когда вы впервые присваиваете значение имени. Таким образом, у вас не может быть неинициализированных переменных в Python.

Это не так в C и C ++. Этот код объявляет переменные i и j, но не присваивает им никаких значений перед попыткой использования их в while l oop. Таким образом, ваш код имеет неопределенное поведение , поскольку переменные содержат любые случайные значения, которые уже присутствовали в памяти, где они выделяются.

Вам необходимо инициализировать переменные прежде чем ваш l oop попытается их оценить:

int i = 0;
int j = 0;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...