c++ - 运行时检查错误3以防万一

标签 c++ c

我的程序已经弄清楚了一半,除了当我去立方一个数字/平方一个数字/显示奇数或偶数而不输入数字时,而不是简单地说明“您还没有输入数字”我得到了运行检查错误 #3 然后是一个非常大的负数。这显然不是我想要发生的事情。

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


//begin function
int main ()
{

//declare variables
int choice;
int number = 0;
int cubed;
int squared;

//menu and begin do while loop
do {


printf("***********************\n");
printf("--Main Menu---\n");
printf("***********************\n");
printf("1.Enter a number\n");
printf("2.Cube the number\n");
printf("3.Square the number\n");
printf("4.Display Even or Odd\n");
printf("5.Quit\n");

printf("Enter your choice:   ");
scanf("%i", &choice);

printf("Your current number is: %i \n", number);

//begin switch and functions
switch(choice){

 case 1: 
      printf("Enter a number\n");
      scanf("%i", &number);
break;

case 2:  

      if (number == 0)
      printf("You have not entered a number\n");
      else 
      cubed= number * number * number;
      printf("Your number cubed is: %i \n", cubed);
break;

case 3:
       if (number == 0)
       printf("You have not entered a number\n");
       else
       squared=  number * number;
       printf("Your number squared is: %i \n", squared);
break;
case 4:
      if (number == 0)
       printf("You have not entered a number\n");
       else if
      (number % 2 ==0)
      printf("Your number squared is even!\n");

      else 

      printf("Your number is odd!\n");

break;

case 5:
      printf("Goodbye!!!!\n");
system("pause");
break;

default:
      printf("Was not 1 through 5\n");
break;
}// end switch and functions








} while (choice!=5); 


} //end function

最佳答案

C 不会初始化变量,因此您必须这样做。如果你不初始化,你的变量将等于内存位置的任何内容,因此它是不可预测的。在您的情况下,您应该用负值初始化数字以强制首先输入数字。整数数=-1;

关于c++ - 运行时检查错误3以防万一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31128805/

相关文章:

c++ - 为什么没有任何内容写入文本文件?

c++ - 使用 xerces-c 删除不需要的节点

c++ - 表达式模板的核心功能 : assignment operator sub-template type?

自定义 malloc() 实现头设计

c++ - 转换回早期类型

python - 嵌入式 Python 的骨架上出现段错误?

c++ - 使用 C11 样式 for 循环删除 vector 元素时出错

c++ - 无法使此代码在 MSVC 2015 和 GCC 7.3 之间交叉编译

c - 有没有一种简洁的方法可以在 C 中创建位掩码?

c - 套接字编程中从客户端获取char()