【问题标题】:C Program gives funny output in VSCode but runs fine in online compilerC 程序在 VSCode 中给出了有趣的输出,但在在线编译器中运行良好
【发布时间】:2022-11-27 08:15:34
【问题描述】:

我从我的一个朋友那里收到了一个代码,它给出了垃圾输出,因此我也尝试在我的 PC 上运行它。我也遇到了同样的问题,我不知道如何解决。 下面是接受和显示来自用户的一些银行客户信息并显示的代码。

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

typedef struct Customer {
    char name[20];
    int date;
    int month;
    int year;
    int amount;
    int type_of_account;
} cus;

void display(int n);
void data_entry_of_customers(int n);

int main() {
    int i, n, choices;
    printf("\n Enter the number of customer you want to enter their data : ");
    scanf("%d", &n);
    do {
        printf("\n Enter your choice :");
        scanf("%d", &choices);
        switch (choices) {
        case 1:
            data_entry_of_customers(n);
            break;

        case 2:
            display(n);
            break;

        case 3:
            exit(0);
            break;

        default:
            {
                printf("\n Invalid Choice");
            }
        }
        i++;
    } while (choices != 3);
    getch();
    return 0;
}

void data_entry_of_customers(int n) {
    cus c[n];
    int i;
    for (i = 0; i < n; i++) {
        printf("\n Enter the name of the customer%d : ", i + 1);
        scanf("%s", c[i].name);
        printf("\n Enter the date when the account was opened by customer : ");
        scanf("%d", &c[i].date);
        printf("\n Enter the month when the account was opened by customer : ");
        scanf("%d", &c[i].month);
        printf("\n Enter the year when the account was opened by customer : ");
        scanf("%d", &c[i].year);
        printf("\n Enter the amount disposited by the customer : ");
        scanf("%d", &c[i].amount);
    }
}

void display(int n) {
    cus c[n];
    int i;
    for (i = 0; i < n; i++) {
        printf("\n The name of the customer%d is %s", i + 1, c[i].name);
        printf("\n The date-month-year when the account was opened by customer%d is %d-%d-%d", i + 1, c[i].date, c[i].month, c[i].year);
        printf("\n The amount when the account was opened by customer%d is %d", i + 1, c[i].amount);
        printf("\n");
    }
}

我最初尝试在我的代码中查找错误,但它对我来说看起来不错,因此我继续使用在线编译器,现在我对如何解决 IDE 的问题一无所知

【问题讨论】:

  • cus 是辅助函数中的局部变量。

标签: c visual-studio-code gcc


【解决方案1】:

cus 数组在displaydata_entry_of_customers 函数中都被定义为局部变量。当函数返回时,输入的值将丢失,display函数中cus的内容不确定,从而产生未定义的行为(垃圾输出)。

如果碰巧两个函数中 cus 数组的位置和内容恰好相同,则程序可能看起来像预期的那样运行。

您应该将数组的定义更多地传递给main 函数并将其传递给data_entry_of_customers()display()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-08
    • 2016-01-02
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2019-06-20
    相关资源
    最近更新 更多