首页 > 解决方案 > 多个`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;
}

标签: c++cin

解决方案


除了缺少对错误用户输入的检查之外,逻辑看起来很合理。添加一个简单的错误输入检查后

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. 如果您必须支持这样的数字,请考虑使用任意长度的整数库。


推荐阅读