【问题标题】:Why is my code returning 0.00?为什么我的代码返回 0.00?
【发布时间】:2017-07-16 21:18:21
【问题描述】:
#include <stdio.h>
#include <math.h>

float math(int, int, int, int, int, float, float, float);

main() {
  int a, b, c, d, e;
  float sum, avg, sd;
  printf("Enter Five Integers->");
  scanf("%d%d%d%d%d", &a, &b, &c, &d, &e);
  math(a, b, c, d, e, sum, avg, sd);
  printf("Sum=%.2f\nAverage=%.2f\nStandard Deviation=%.2f", sum, avg, sd);
}

float math(int a, int b, int c, int d, int e, float sum, float avg, float sd) {
  sum = a + b + c + d + e;
  avg = (sum) / 5;
  sd = pow(
      ((pow(a - avg, 2) + pow(b - avg, 2) + pow(c - avg, 2) + pow(d - avg, 2),
        pow(e - avg, 2)) /
       5),
      0.5);
  return sum, avg, sd;
}

我的程序总是返回答案 0.00。谁能解释我的代码有什么问题?

【问题讨论】:

  • 请正确缩进您的代码。阅读逗号运算符的作用,您没有分配返回值;变量是按值传递的,因此在函数中更改它们根本没有帮助。
  • 单步调试代码时调试器会告诉你什么?
  • 您的math 函数不会返回您认为的结果(阅读the comma operator)。您可能需要find a good beginners book 并阅读更多关于函数以及参数和返回值如何工作的信息。
  • 还有什么代码应该“返回”反正。
  • 感谢您的帮助。我的代码应该“返回”输入的五个整数的总和、平均值和标准差。

标签: c return function-call comma-operator


【解决方案1】:

TL;DR因为,您的代码调用了undefined behavior,无法证明输出的合理性。

首先要详细说明声明

 return sum, avg, sd;

没有做你认为它正在做的事情。它不会一起返回三个值,而是由于使用了comma operator,它只返回sd

也就是说,您没有在代码中的任何地方收集函数调用的返回值,因此您无法在调用者那里获得从函数调用返回的任何有效输出。

在那之后,你最终会使用

 printf("Sum=%.2f\nAverage=%.2f\nStandard Deviation=%.2f", sum, avg, sd);

其中,提供的变量(自动、局部变量)保持未初始化状态,本质上是在尝试使用调用 undefined behavior 的不确定值。

最后,对于托管环境,main() 的一致性签名至少应该是 int main(void)

解决方案:您需要

  • 将指针传递给那些你想在其中存储被调用函数结果的变量,然后在调用者中你可以使用它们来检索更新的值。

  • 形成一个结构,其中包含您希望为其返回计算值的所有变量,填充并返回该结构。然后,在调用者中,将返回的值收集到另一个结构类型变量中,然后使用单个成员元素打印该值。

【讨论】:

  • 感谢您的帮助。前几天刚开始编程,还没有学过指针,所以不知道怎么用。
  • 过几天我会尝试用指针重写这段代码。谢谢你的帮助!
【解决方案2】:

您的代码中的取点很少。

  1. 在 C 语言中,您不能从函数返回超过 1 个值。您正在尝试返回 3 个值,因为它们使用“逗号(,)”分隔,只返回最后一个值。
  2. 两个函数的局部变量之间存在差异。如果没有适当的参考,您不能在 1 个函数中分配它们并在其他函数中使用它。
  3. 您将函数设为“call by value”(在链接中了解更多信息)。如果您希望更改值,则应使用“call by refernce”,它使用指针。

所以对您来说最简单的解决方法是使用全局变量。

void math(int, int, int, int, int);     //Changed function declareation
 double sum,avg,sd; //New global variables

 int main()
 {
    int a, b, c, d, e;
    printf("Enter Five Integers->");
    scanf("%d%d%d%d%d", &a, &b, &c, &d, &e);
    math(a, b, c, d, e);        //Changed function calling
    printf("Sum=%.2f\nAverage=%.2f\nStandard Deviation=%.2f\n", sum, avg, sd);
    return 0;
}

 void math(int a, int b, int c, int d, int e)
 {
    sum = a + b + c + d + e;
    avg = (sum) / 5;
    double result = (pow(a - avg, 2) + pow(b - avg, 2) + pow(c - avg, 2) +  pow(d - avg, 2) + pow(e - avg, 2) ) / 5;
    sd = pow(result , 0.5);
 }

【讨论】:

  • 使用全局变量并不是解决问题的好方法。有用;它甚至可能相当容易;不过,这不是一个好习惯。该场景也存在其他问题(不是您制作的 - 原始场景)。特别是,传递固定数量的值是奇数。更好的解决方案是将半任意数量的值读入数组,函数中的代码会处理数组。
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 2016-02-16
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多