Calculate the work of the honorary numbers



  • Objective: I can't figure out why the code doesn't work:

    #include <ctime>
    #include <stdlib.h>
    #include <stdio.h>
    #include <corecrt_math.h>
    #include <time.h>
    

    int main(){
    const int N = 20;
    int arr[N];
    //Заполнение случайными числами
    srand(time(0));
    for (int i = 0; i < N; i++)
    {
    arr[i] = rand() % 101 - 50; //[-50;50]
    printf_s("arr[%d] = %d\n", i + 1, arr[i]);
    }
    //Обработка массива-произведение четных чисел массива
    int dob = 1;
    for (int i = 0; i < N; i++)
    {
    if (arr[i] % 2 == 0);
    {
    printf("%d",arr[i]);
    dob = dob * arr[i];
    }

    }
    printf("\ndob = %d\n", dob);
    return 0;
    

    }



  • Your main mistake is in this line: if (arr[i] % 2 == 0); a more specific ; I don't know who's supposed to be there if she's cleaned up, the code will work.

    But naturally, it's not all the mistakes you made:

    1. You import libraries you don't need.
    2. When imported, you write <название.h>although these libraries do not require such a requirement
    3. In the range of numbers [-50;50] You're using. intin which there are only four baytes that are almost always missing
    4. No case processing 0And you need it that way. 0 % 2 == 0 Come back. truealthough 0 usually not counted as an even

    I fixed these moments and the code came out like this:

    #include <ctime>
    #include <cstdlib>
    #include <cstdio>
    

    int main() {
    const int N = 20;
    int arr[N];
    // Заполнение случайными числами
    srand(time(0));
    for (int i = 0; i < N; i++) {
    arr[i] = rand() % 101 - 50; //[-50;50]
    printf_s("arr[%d] = %d\n", i + 1, arr[i]);
    }
    // Обработка массива - произведение четных чисел массива
    long long dob = 1;
    for (int i = 0; i < N; i++) {
    if (arr[i] % 2 == 0 && arr[i] != 0) {
    printf("%d ", arr[i]);
    dob = dob * arr[i];
    }
    }
    printf("\ndob = %lld\n", dob);
    return 0;
    }

    P.S. We can rewrite a little bit to read. Instead,

    for (int i = 0; i < N; i++) {
    if (arr[i] % 2 == 0 && arr[i] != 0) {
    printf("%d ", arr[i]);
    dob = dob * arr[i];
    }
    }

    Write that:

    for (int i : arr) {
    if (i % 2 == 0 && i != 0) {
    printf("%d ", i);
    dob = dob * i;
    }
    }


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2