@gliese581d
Учусь

Как вывести сумму итераций цикла?

Прохожу курс cs50, задача звучит так:

Задача
Complete the implementation of population.c, such that it calculates the number of years required for the population to grow from the start size to the end size.

Your program should first prompt the user for a starting population size.
If the user enters a number less than 9 (the minimum allowed population size), the user should be re-prompted to enter a starting population size until they enter a number that is greater than or equal to 9.

Say we have a population of n llamas. Each year, n / 3 new llamas are born, and n / 4 llamas pass away.

For example, if we were to start with n = 1200 llamas, then in the first year, 1200 / 3 = 400 new llamas would be born and 1200 / 4 = 300 llamas would pass away. At the end of that year, we would have 1200 + 400 - 300 = 1300 llamas.

To try another example, if we were to start with n = 1000 llamas, at the end of the year, we would have 1000 / 3 = 333.33 new llamas. We can’t have a decimal portion of a llama, though, so we’ll truncate the decimal to get 333 new llamas born. 1000 / 4 = 250 llamas will pass away, so we’ll end up with a total of 1000 + 333 - 250 = 1083 llamas at the end of the year.


Мое решение: так как цикл продолжается до тех пор пока сумма рассчитанная по формуле x=n+(n/3)-(n/4) где n это кол-во популяции на старте, меньше чем кол-во популяции в конце, то к-во итерации = кол-во лет, нужных для достижения кол-ва конечной популяции.
Код:

#include <cs50.h>
#include <stdio.h>

int start_int();
int end_int();
int calculate();

int main(void) {
    int i = start_int();
    int j = end_int(i);
    int h = calculate(j, i);
}

// prompt the user for a starting population size
int start_int(void) {
    int y;
    do {
        y = get_int("set starting population size: ");
    } while (y < 9);
    return y;
}

// prompt the user for an ending population size
int end_int(start_int) {
    int x;
    do {
        x = get_int("set ending population size: ");
    } while (x < start_int);
    return x;
}

int calculate(start_int, end_int) {
    int k;
    int n = 0; //счетчик
    do {
        k = start_int + (start_int / 3) - (start_int / 4);
    } while (k < end_int);
    {
        n++;           //инкремент счетчика
        start_int = k; //подмена полученной суммы на "start_int"
        return start_int; //возврат замененного значения
    }
    printf("%i", n); //не выводит сумму итераций
}


где printf("%i", n); не выводит сумму итераций

результат
~/ $ ./population
set starting population size: 1200
set ending population size: 1300


Подскажите пожалуйста, в чем может быть проблема?
  • Вопрос задан
  • 577 просмотров
Решения вопроса 1
includedlibrary
@includedlibrary
Небольшая рекомендация - указывайте типы аргументов в функциях и сами аргументы в прототипах:
int start_int();
int end_int(int start_int);
int calculate(int start_int, int end_int);


Решение - нужно переписать функцию calculate следующим образом:
  1. n++ нужно перенести в while, чтобы переменная n увеличивалась каждую итерацию.
  2. Установить начальное значение k в start_int, так как k - текущий размер популяции.
  3. Вместо start_int для обновления k использовать само значение k, по правилам обновления размера популяции
  4. Убрать printf, так как функция calculate должна находить количество итераций, его вывод лучше переместить в main.
  5. Убрать скобки вокруг return, оборачивать return в блок нет никакого смысла.
  6. Вернуть n вместо start_int.


int calculate(int start_int, int end_int) {
    int k = start_int; //текущий размер популяции
    int n = 0; //счетчик

    do {
        k = k + (k / 3) - (k / 4);
        n++;           //инкремент счетчика
    } while (k < end_int);

    return n; //возврат количества итераций
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы