c++ - 多个`cin`没有给出正确答案
问题描述
cin
直接用 with输入值1212121221121212 + 34343434343434 = 1246464655464646
没有解决办法。为什么?
#include <iostream>
using namespace std;
int main() {
long int a, b, c;
char op, eq;
cout << "Input the formula: ";
cin >> a >> op >> b >>eq >> c;
long int sum;
if (op == '+') {
sum = a + b;
}
else {
sum = a - b;
}
if (sum == c) {
cout << "Correct";
}
else {
cout << "No Solution";
}
return 0;
}
解决方案
除了缺少对错误用户输入的检查之外,逻辑看起来很合理。添加一个简单的错误输入检查后
if (std::cin >> a >> op >> b >> eq >> c) // testing for valid input
{
...
}
else
{
std::cout << "bad input. Buh-bye!"; // inform user of bad input
}
用户输入1212121221121212 + 34343434343434 = 1246464655464646导致输出错误输入。再见!
错误输入的最可能原因是给出的数字超过了 32 位整数的最大容量(long int
大多数台式计算机上的常见解释)。将数字的容量增加到至少 64 位int_least64_t
似乎可以解决这个问题,至少目前是这样。
#include <iostream>
#include <cstdint> // needed for int_least64_t
int main()
{
int_least64_t a, b, c; // guaranteed larger type
char op, eq;
std::cout << "Input the formula: ";
if (std::cin >> a >> op >> b >> eq >> c) // testing for valid input
{
int_least64_t sum; // guaranteed larger type
if (op == '+')
{
sum = a + b;
}
else
{
sum = a - b;
}
if (sum == c)
{
std::cout << "Correct";
}
else
{
std::cout << "No Solution";
}
}
else
{
std::cout << "bad input. Buh-bye!"; // inform user of bad input
}
return 0;
}
当数字再次变得太大而无法放入int_least64_t
. 如果您必须支持这样的数字,请考虑使用任意长度的整数库。
推荐阅读
- ruby-on-rails - AWS Ruby SDK 中的无效配置选项 `:dynamodb' 错误
- github - Jenkinsfile 中的条件环境变量
- python - 重新排序工作簿python中的一些工作表
- amazon-web-services - TypeError:无法读取未定义的属性“AwsCredentialsProvider”
- ruby-on-rails - Rails 不区分嵌套在相同命名空间中的两个资源
- java - 如果您更改实体标识符,Hibernate 不会从数据库中删除实体。它只是添加新的
- php - php get_headers() 函数 - 有没有办法告诉这个函数不要跟随重定向?
- scipy - Solve_ivp 变量求解函数
- javascript - 如何将字符串拆分为单个字符,其中每个新字符作为 json 对象添加到数组中
- c++ - 无法在 Visual Studio 代码中使用初始化列表初始化向量