【问题标题】:Function not displaying the answer of a calculation函数不显示计算结果
【发布时间】:2015-09-28 06:10:57
【问题描述】:

我对此很陌生,我已经尝试了一切,但我无法让它工作,无论我改变什么,它都只会显示“无效的数学运算”。请帮我解决这个问题。

#include <stdio.h>
#include <math.h>

int fnCalculate (int fn, int sn);

int main()
{
    int fn, sn;
    char op;
    printf("Enter 2 interger values and math operation [+] [-] [*] : ");
    scanf("%d %d %c", &fn, &sn, &op);
    printf("%d", fnCalculate(fn,sn));
    getch();
    return 0;

}
int fnCalculate (int fn, int sn)
{
char op;
switch(op){

case '+' : printf("%d + %d = %d", fn, sn, fn+sn);break;
case '-' : printf("%d - %d = %d", fn, sn, fn-sn);break;
case '*' : printf("%d * %d = %d", fn, sn, fn*sn);break;
default : printf("Invalid Math Operation");break;

}
}

【问题讨论】:

  • 您需要将op 传递给函数 - 它不是全局的..

标签: c function switch-statement


【解决方案1】:

您必须向函数发送操作字符。 op in 函数未初始化并持有垃圾值。

void fnCalculate (int fn, int sn, char op)
{
    switch(op){

    case '+' : printf("%d + %d = %d", fn, sn, fn+sn);break;
    case '-' : printf("%d - %d = %d", fn, sn, fn-sn);break;
    case '*' : printf("%d * %d = %d", fn, sn, fn*sn);break;
    default : printf("Invalid Math Operation");break;
    }
}

这样称呼:

fnCalculate(fn,sn,op);

此外,它应该返回一个int 值。它没有返回任何东西,所以那里还有另一个问题。或者将签名更改为void,然后调用函数,而不是printf

【讨论】:

  • 哦,是的。对此感到抱歉。
  • 建议在示例中也将返回类型更改为 void 或至少在示例中返回一些内容
【解决方案2】:

您还需要更改函数定义以接受op 的值,并且在调用时,您需要传递op 的值。否则,在您当前的函数中,

char op;
switch(op){

正在尝试读取调用未定义行为的未初始化自动局部变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2017-10-19
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多