为什么当我输入大量数字时,我的计算器程序开始闪烁和滚动
why does my calculator program start flashing and scrolling when i enter a large number
我的程序是一个计算器,目前只做加法和减法,但是当我输入一个大数字时,它开始闪烁和滚动。 它适用于小数字。 该程序不长,所以就在这里。 问题 https://youtu.be/Fa03WtgXoek 的YouTube视频
#include <iostream>
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
return a;
}
int add()
{
int x = GVFU();
int y = GVFU();
int z = x + y;
std::cout <<z <<std::endl;
return 0;
}
int subtract()
{
int x = GVFU();
int y = GVFU();
int z = x - y;
std::cout <<z << std::endl;
return 0;
}
int main()
{
for ( ; ; )
{
std::cout << "enter 1 for addition and 2 for subtraction";
int c;
std::cin >> c;
if (c==1)
{
add();
}
if (c==2)
{
subtract();
}
std::cout << "press 1 to end";
int e;
std::cin >>e;
if (e==1)
{
return 0;
}
}
}
如果您尝试从 cin 读取值,并且读取的值与预期格式不匹配,则会导致流失败,并且所有将来的读取操作将立即返回而不读取任何内容。
独立地,int 类型的整数值C++具有最小值和最大可能值,具体取决于您使用的编译器和系统。如果在输入数字时超过该值,cin 将认为读取失败。
综上所述,一旦您输入的值太大,程序将继续通过程序中的主循环运行,提示输入值,立即返回而不实际获取用户输入,然后计算垃圾值。
要解决此问题,您需要 (1( 只希望用户不要输入任何意外内容,或者 (2( 让用户输入更可靠。关于如何在堆栈溢出上执行选项(2(,有许多很好的解释,现在您知道问题的根本原因是什么,希望您可以修复代码并正常工作!
使用
std::cout << std::numeric_limits<int>::max() << std::endl;
并包括#include <limits>
,您将在机器上找到最大int
值。
系统上的int
可能是一个32-bit
signed
two's complement
的数字,这意味着它可以表示的最大值是2,147,483,647
。 如果添加更大的数字流将失败,并且所有下一个读取操作将返回而不读取任何内容。
使用允许您插入更大数字的unsigned long long
。
您将输入为 " int ",int 的值范围介于 -2,147,483,648 到 2,147,483,647 之间。 这意味着,如果超过此值 2,147,483,647,则不能将其存储为 integer(int( 类型。 对于如此大的数字,您可能应该使用 Long 数据类型。
如果用户输入超过int limit
,则可以在代码中添加以下检查
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "Invalid input " << endl;
}
return a;
}
如果号码无效,我也会添加退出
#include <iostream>
#include <cstdlib>
using namespace std;
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "Invalid input " << endl;
std::exit(EXIT_FAILURE);
}
return a;
}
注意:您还可以提供更多信息,而不仅仅是"无效输入" 输出,如大小或限制信息
enter 1 for addition and 2 for subtraction1
enter number4535245242
Invalid input
Program ended with exit code: 1
- 我在c ++矩阵计算器程序中找不到错误
- 桌面计算器出现问题.C++程序设计语言
- 为什么当我输入大量数字时,我的计算器程序开始闪烁和滚动
- 如何调试我的C++ BMI 计算器程序?
- C++:我的简单计算器程序无法打印出来。我也认为我的变量命名不正确
- Pi计算器程序每次运行时都会给出不同的输出
- C 中的控制台计算器程序无法正常工作
- 工资计算器(加班工资)需要高级程序员的帮助
- 计算贷款计算器程序的总利息的问题(C++)
- 在 c++ 计算器程序中重载 '+' 运算符时无法获得正确的输出
- 工资计算器程序
- 简单的计算器程序出了什么问题
- 程序和计算器答案之间的差异为0.5
- C++计算器程序
- C++构建三角计算器的程序
- 计算器程序总是输出 0 - 我做错了什么
- C++计算器程序正在跳过if语句,即使它编译得很好
- 第一个C++程序帮助(计算器)
- 我从哪里开始编写自己的计算器程序
- 如何在零钱计算器程序中花2.30美元找对零钱