【问题标题】:Easy calculator简易计算器
【发布时间】:2023-04-03 01:50:01
【问题描述】:

大家好,我是C++自学的初学者。 今天我试着做一个简单的计算器,但调试器不断地向我显示同样的错误。使用单化变量 "X" ;单化变量使用“Z”

代码如下:

#include <iostream>
using namespace std;

int main()
{
    float x, z, a;
    a = x + z;



    cout << "Welcome to the calculator" << endl;
    cout << "State the first number " << endl;
    cin >> x ;
    cout << "State the second number " << endl;
    cin >>  z ;
    cout << "If you wanted to time number" << x << "by this number" << z << "The result would be : " << a << endl;



    system("pause");
    return 0;
} 

【问题讨论】:

  • 请不要用“改进”更新问题;它使答案变得毫无意义。 (我已将其回滚。)接受一个有帮助的答案,如果您有任何进一步的问题,请发布另一个问题。 (你应该从this list 给自己买一本书并阅读有关“作业”的内容。)
  • 有时少即是多,“大家好”无缘无故地排除了大约一半的社区;)
  • 添加到 molbdnilos 评论:如果你想分享你的固定/改进的代码,回答你自己的问题是完全可以的,但你真的不应该修复问题本身的代码

标签: c++ calculator


【解决方案1】:

在阅读xz 之后,您应该初始化变量并计算a。看看这个:https://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/

#include <iostream>
using namespace std;

int main()
{
    float x = 0.0f, z = 0.0f, a = 0.0f;

    cout << "Welcome to the calculator" << endl;
    cout << "State the first number " << endl;
    cin >> x ;
    cout << "State the second number " << endl;
    cin >>  z ;
    a = x + z;
    cout << "If you wanted to time number" << x << "by this number" << z << "The result would be : " << a << endl;



    system("pause");
    return 0;
} 

【讨论】:

  • 您应该删除第一个a = x + z 以避免混淆。
  • 好的,我这样做了。但我试图做一个改进,这次没有错误,但它只是没有做这项工作......
  • 我刚刚解决了,bz 将数学运算的部分移到欢迎部分和加号部分的下方。
【解决方案2】:

你做事的顺序很重要。

int x = 5, z = 2;

int a = x + z; // a is 7

z = 5; // a is still 7

a = x + z; // now a is updated to 10

因此,在您的代码中,当您执行 a = x + z; 时,xz 都未初始化。使用未初始化的变量是未定义的行为。

要解决此问题,请在将 xz 输入值之后将 a = x + z; 移动到。

【讨论】: