You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言Calculate_age_when_Trump_elected函数功能异常求助

Fixing the Age Calculation Output Issue

Let's break down the problems in your code and fix them step by step:

1. Incorrect Return Value in Calculate_age_when_Trump_elected

Your function correctly computes the age as YEAR_TRUMP_ELECTED - year_born, but then you return 0 instead of the calculated result. This means the function never actually sends back the age value you worked out!

2. Wrong Variable Used in printf

In your main function, you assign the function's result to age_when_Trump_elected, but then you print year_born (the user's birth year) instead of this computed variable. That's why the output only shows the birth year instead of the age when Trump was elected.

Fixed Code

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include "terminal_user_input.c"
#define YEAR_TRUMP_ELECTED 2016

// A very basic read boolean function
bool read_boolean(const char* prompt) {
    my_string answer;
    bool result;
    answer = read_string(prompt);
    answer.str[0] = (char) tolower(answer.str[0]);
    switch (answer.str[0]) {
        case 'n':
            result = false;
            break;
        case 'x':
            result = false;
            break;
        default:
            result = true;
    }
    return result;
}

int Calculate_age_when_Trump_elected(int year_born) {
    int result;
    result = YEAR_TRUMP_ELECTED - year_born;
    return result; // Return the computed age instead of 0
}

int main() {
    my_string name;
    int age_when_Trump_elected;
    int year_born;
    bool brexiter;

    name = read_string("What is your name? ");
    year_born = read_integer("When were you born? ");
    age_when_Trump_elected = Calculate_age_when_Trump_elected(year_born);
    printf("You were %d years old when Trump was elected\n", age_when_Trump_elected); // Use the correct variable here
    brexiter = read_boolean("Are you a Brexit supporter? ");

    if (brexiter == true) {
        printf("%s is a Brexit supporter\n", name.str);
    } else {
        printf("%s isn't a Brexit supporter\n", name.str);
    }

    read_string("Type 'exit' to continue ");
    return 0;
}

Key Changes Explained

  • In Calculate_age_when_Trump_elected: Swapped return 0; with return result; so the function returns the actual age calculation instead of a dummy value.
  • In main's printf: Replaced year_born with age_when_Trump_elected to print the computed age, not the birth year.
  • Small grammar fixes: Adjusted prompts like "When you were born?" → "When were you born?" and "Are u a Brexit support?" → "Are you a Brexit supporter?" for clarity (these don't affect functionality but make the program more user-friendly).

内容的提问来源于stack exchange,提问作者Chi Kit Chek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:34:36