首页 > 解决方案 > 简易计算器

问题描述

大家好,我是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;
} 

标签: c++calculator

解决方案


你做事的顺序很重要。

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;这两项操作x并且z未初始化时。使用未初始化的变量是未定义的行为。

要修复它,请a = x + z;在输入值后将 移至xz


推荐阅读