为什么我得到,变量未初始化错误?

时间:2021-05-29 20:20:45

标签: c

#include <stdio.h>
#include <conio.h>
void Calculator(); 

void main() 
{
    Calculator(); 
    getch();
} 

void Calculator() 
{
 int n,j;
 char f1;
 double t;
 printf("please enter two numbers");
 scanf("%d%d",&n,&j);
 printf("please enter the syboml you want ( * / + or -)");
 scanf("%c",&f1);
 if( f1 == '+')
    t = n + j;
 if (f1 == '-')
    t = n-j;
 if (f1 == '*')
    t = n*j;
 if (f1 == '/')
    t = n/j;
 printf("%f" ,t);
}

3 个答案:

答案 0 :(得分:2)

在最后的 printf 中,您使用的是从未初始化过的 t,如果不满足这些 if 条件中的任何一个,它可能会持有垃圾值。

考虑初始化 t(一个简单的 = 0 即可)或在某处添加一个 else 子句

编辑:

当我在做的时候,我也做了一些改变,以确保第二个 scanf 在不使用 /n 的情况下忽略尾随的 fflush

编辑 2:

正如 HAL9000 所建议的,假设初始化为 0 就足够了是错误的。我修改了程序的第二部分以使用 switch-case 并最终拒绝一个无效的运算符。

最终代码如下

#include <conio.h>
#include <stdio.h>
void Calculator();

int main() {
  Calculator();
  getch();
  return 0;
}

void Calculator() {
  int n, j;
  char f1;
  double t;
  printf("please enter two numbers: ");
  scanf("%d%d", &n, &j);
  printf("please enter the symbol you want ( * / + or -): ");
  scanf(" %c", &f1);
  switch (f1) {
    case '+':
      t = n + j;
      break;
    case '-':
      t = n - j;
      break;
    case '*':
      t = n * j;
      break;
    case '/':
      t = (float)n / j;
      break;
    default:
      printf("Invalid symbol, please use ( * / + or -)\n");
      return;
  }
  printf("%f\n", t);
}

答案 1 :(得分:0)

在某些编译器中,您可能会遇到此 t is not initialized 错误,因为您的代码永远不会询问请输入您想要的符号(* / + 或 -),因为 scanf("%c",&f1); 将输入作为尾随换行符,所以 t 永远不会被初始化。我在 Mac 上的 GCC 编译器中运行了您的代码,但输出为 0.0000,因为在您的情况下 t 永远不会被初始化。

你可以只吃掉尾随的字符,你可以使用 getchar(); 或者你也可以在格式字符串中放置一个空格,例如scanf(" %c",&f1); 使用换行符。

    void Calculator() 
{
 int n,j;
 char f1;
 double t;
 printf("please enter two numbers");
 scanf("%d%d",&n,&j);
 printf("please enter the syboml you want ( * / + or -)");
 scanf(" %c",&f1);
 if( f1 == '+')
    t = n + j;
 if (f1 == '-')
    t = n-j;
 if (f1 == '*')
    t = n*j;
 if (f1 == '/')
    t = n/j;
 printf("%f" ,t);
}

答案 2 :(得分:0)

并非每个程序路径都指向 t 变量的赋值。所以可以在未初始化的printf中使用。

switch(f1)
{
 case '+':
    t = n + j;
    break;
 case '-':
    break;
    t = n-j;
 case '*':
    t = n*j;
    break;
 case '/':
    t = n/j;
    break;
 default:
    t = 0;
    break;
}

现在 t 将始终被赋值。

一些补充说明:

  1. 始终检查 scanf 的返回值
  2. 您的 main 定义无效。如果 main 不带任何参数,则必须是 int main(void)
相关问题