试图编写一个程序,其中各个功能都执行不同的任务,并且它们共享变量

问题描述 投票:0回答:1

我正在尝试制作一个程序,该程序首先要求用户每年输入12个值。然后,需要比较第一年“ i”月的值是否小于第二年“ i”月的值。然后,它需要花费几个月的时间并输出该值。到目前为止,这是我的代码,由于其他函数中的变量“未定义”,我正在努力在函数之间共享值。我试图通过调用这些函数中的函数将变量输入到其他函数中,但这是行不通的。

谢谢您的帮助!

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

void DisplayInstructions()
{
    printf("This program is going to take values for the sales in year 1 and year 2 and then compute how many months were more successful in year 2 \n");

    float year1[12];
    float year2[12];
    int i = 0;
    int months = 0;

    for(i=0; i<12; i++)
    {
        int k = i + 1;
        printf("Enter the monthly sales for the first year and for the %d month: \n", k);
        scanf_s("%f", &year1[i]);

        printf("Enter the monthly sales for the second year and for the %d month: \n", k);
        scanf_s("%f", &year2[i]);
    }
}

void HigherSales()
{
        DisplayInstructions();

        if(year1[i] < year2[i])
        {
            months = months + 1;
        }
}

void DisplayAnswer()
{
    HigherSales();
    printf("%d\n", months);
}

void main()
{
    DisplayInstructions();
    HigherSales();
    DisplayAnswer();
    system("pause");
}
c++ c
1个回答
0
投票

main中声明变量,并使用参数和返回值在不同部分之间进行通信。(请考虑值而不是变量。)

您的分工有点奇怪-我会写这样的东西:

void ReadInputs(float *year) {
    for(int i = 0; i < 12; i++) {
        int k = i + 1;
        printf("Enter the sales for the %d month: \n", k);
        scanf_s("%f", &year[i]);
    }
}

int HigherSales(const float* year1, const float* year2) {
    int months = 0
    for(int i = 0; i < 12; i++) {
        if(year1[i] < year2[i]) {
            months = months + 1;
        }
    }
    return months;
}

int main()
{
    printf("This program is going to take values for the sales in year 1 and year 2 and then compute how many months were more successful in year 2 \n");
    float year1[12] = {};
    printf("Enter the monthly sales for the first year. \n");
    ReadInputs(year1);
    float year2[12] = {};
    printf("Enter the monthly sales for the second year. \n");
    ReadInputs(year2);
    int months = HigherSales(year1, year2);
    printf("%d\n", months);
}

((这是一个基本的“读-写”结构,在许多情况下很有用。)

© www.soinside.com 2019 - 2024. All rights reserved.