按值传递参数并将相同的参数返回给调用函数[关闭]

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

我在 C 编程课上,老师说由于技术原因,将参数按值传递给某个函数并将修改后的参数返回给调用函数不是一个好习惯。他没有说明技术原因是什么?

我知道通过引用传递值意味着什么,我知道如何使用它,我想我知道通过值传递和通过引用传递之间的区别。我只是无法理解为什么我不能在某些情况下,将参数从

main
按值传递给函数,修改它,然后将其返回给
main

这是我的程序。我老师说:“因为

sum
中的
askDecimals
变量是一个值参数(通过值传递),它不能向调用程序返回信息”
.

我明白,我在这里通过在

sum
函数中声明
main
并将其按值传递给
askDecimals
来进行不良实践。相反,我应该在
sum
函数中声明
askDecimals
变量。

但不管怎样,我老师的评论至少对我来说,听起来你永远无法将值作为参数传递并返回它。

如果我理解错了老师,请现在纠正我。

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

void askName(char *pName) {
    printf("Enter a name, maximum 20 characters: ");
    fgets(pName, 20, stdin);
    pName[strlen(pName)-1] = '\0';
    return;
}

float askDecimals(float sum, int count) {
    float decimal;
    for (int i = 0; i < count; i++) {
        printf("Enter a decimal number: ");
        scanf("%f", &decimal);
        getchar();
        sum = sum + decimal;
    }
    return sum;
}

void printInfo(int count, char *pName, float sum, float avg) {
    printf("You entered the name: %s.\n", pName);
    printf("You entered the number: %d.\n", count);
    printf("The sum of the decimal numbers was: %f.\n", sum);
    printf("The average of the decimal numbers was: %.2f.\n", avg);
    return;
}

int main(void) {
    char name[20];
    int count;
    float sum = 0;
    float avg;
    askName(name);
    do {
        printf("Enter a positive integer: ");
        scanf("%d", &count);
        getchar();
        if (count <= 0) {
            printf("You must enter a positive integer. Please try again.\n");
        }
    } while (count <= 0);

    sum = askDecimals(sum, count);
    avg = sum / count;
    printInfo(count, name, sum, avg);

    return 0;
}
c
© www.soinside.com 2019 - 2024. All rights reserved.