为什么当我输入大量数字时,我的计算器程序开始闪烁和滚动

why does my calculator program start flashing and scrolling when i enter a large number

本文关键字:程序 计算器 我的 开始 闪烁 滚动 输入 数字 为什么      更新时间:2023-10-16

我的程序是一个计算器,目前只做加法和减法,但是当我输入一个大数字时,它开始闪烁和滚动。 它适用于小数字。 该程序不长,所以就在这里。 问题 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-bitsignedtwo'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