提问者:小点点

为什么这个C++程序不能正常运行?


现在我正在学习C++我做了我的第一个小程序加法计算器,我写两个数字,它把它们相加。你能告诉我为什么我的输出是0吗?

#include <iostream>
#include <string>
using namespace std;

int main () {
    int a;
    int b;
    string number1;
    string number2;
    number1 = a;
    number2 = b;
    int output;
    output = a + b;
    getline (cin, number1);
    getline (cin, number2);
    cout << output;
    }

输出:

1
1
0

共1个答案

匿名用户

按顺序逐步检查代码,您将看到问题所在:

int main () {
    int a;
    int b;
    string number1;
    string number2;
    number1 = a;
    number2 = b;
    int output;
    output = a + b;
    getline (cin, number1);
    getline (cin, number2);
    cout << output;
}

你定义了四个变量,用一种奇怪的方式摆弄其中的两个,然后把输出计算为a+B。

此时,您还没有与用户进行实际交互。完成所有操作,然后接受两个值(作为字符串)并输出先前计算的值。

您从不使用从输入中提取的值,而在执行其他操作之后才使用。

不妨试试这个:

#include <iostream>
#include <string>

int main () {
    std::string number1;
    std::string number2;
    std::getline (std::cin, number1);
    std::getline (std::cin, number2);

    int a = std::stol(number1);
    int b = std::stol(number2);
    int output = a + b;
    std::cout << output << std::endl;
}

也就是说,定义字符串,然后从用户那里获取它们。

STD::短距起落是“从弦到长”。它将字符串转换为数字。

剩下的应该说得通。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|程序|运行)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?