簡體   English   中英

do-while function 不返回值

[英]do-while function not returning value

#include <stdio.h>
#include <cs50.h>
int counter(int n,int x, int y);
int main (void){
    //prompt for start and end year;
    int start;
    do{
        start = get_int("starting population no: ");
    }
    while( start < 9);
    int end;
    do {
        end = get_int("ending population no: ");
    }
    while (end < start);
    // calculate number of years until we reach threshold
    int years = 0;
    counter(years, start, end);
}
int counter(int n, int x, int y){
    do {
        x = x + x / 3 - x / 4;
        n++;
    }
    while(x < y);
    return n;
    printf("years: %i", n);
}

低於 function 的計數器應該返回我們這一年的值。 但它沒有返回那個值 idk 什么不起作用,如果我的 while 條件運行良好,因為它沒有返回任何東西。 請告訴我哪里錯了。

它正在返回一個值,但您什么都不做。

counter(years, start, end);

應該

int n = counter(years, start, end);
printf("years: %i", n);

您確實有一個嘗試打印該值的語句,但它無法訪問,因為它在return之后。 始終啟用編譯器的警告。 它會發現這個錯誤。 (對於gcc ,我使用-Wall -Wextra -pedantic -Werror 。)

你可能想要這樣的東西:

    ...
    // calculate number of years until we reach threshold
    int years = counter(0, start, end);
    printf("years: %i", years);
}

int counter(int n, int x, int y){
    do {
        x = x + x / 3 - x / 4;
        n++;
    }
    while(x < y);
    return n;
    // don't printf n here, it's pointless
}

其他地方可能錯誤較多,我沒查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM