首页 > 解决方案 > 我对变量如何工作的理解是错误的吗?

问题描述

在此处输入图像描述

你好。我对 C++ 和一般编程非常陌生。我正在尝试通过玩弄我已经理解的小组件来建立我的信心,直到我在学习更多之前尽可能地熟悉。然而,我对自己感到困惑和沮丧,因为我似乎无法让这段简单的代码工作。我希望任何读到这篇文章的人都能理解我的尝试,并能告诉我哪里出错了。谢谢,麻烦您了。

#include <iostream>

int main(int argc, const char * argv[]) {


    char computer[100];
    char something[100];



    double price;
    double price2;
    double total = (price + price2);
    double budget;
    if (budget < total){ double need = total - budget;}
    if (budget > total ){ double surplus = budget - total;}
    double perday = total / 365;
    double remain = budget - perday;
    int A;

    std::cout << "Please tell me, the 'name' of the new computer that you would like to buy.\n";
    std::cin >> computer;
    std::cout << " How much does this " << computer << " cost?\n";
    std::cin >> price;
    std::cout << "Cool! Now tell me something else you would like to buy.\n";
    std::cin >> something;
    std::cout << "How much does " << something << " cost?\n";
    std::cin >> price2;
    std::cout << "I need to know your technology budget:\n £";
    std::cin >> budget;


    if (budget >= total)
    {std::cout << "Wow you have enough cash to get both " << computer << " and " << something << "\n with a surplus budget of £" << surplus;}

    else (budget < total) {
    std::cout << "I am sorry you lack the necessary funds right now. \n";
    std::cout << "Would you like to hear a payment plan?\n 1 for yes / 2 for no \n";
    std::cin >> A;
    }

    if (A = 1) {
            std::cout << "If you wanted to buy both " << computer << " and " << something << " \n by this time next year, you could pay £" << perday << "each day from now\n ";
            std::cout << "If I take today's payment now, you will have £" << remain << "left of your budget";}
        else return 0;}
}

标签: c++variablessyntax

解决方案


首先,在一个范围内声明一个变量是一个坏习惯,除非您打算只在该范围内使用该变量。

if (budget < total){ double need = total - budget;}
if (budget > total ){ double surplus = budget - total;}

在这种情况下,need只能surplus在这些之间生活{ },不能在它们之外使用。如果您想稍后在程序中使用它们,请确保将它们声明为超出范围。

我注意到的另一件事是在编程语言中分配运算符=用于向变量添加值。在您的情况下,if (A = 1)将不起作用,因为 cpp 不会检查 A 是否为 1,但它会将 A 分配为 1。您应该做的是检查if (A == 1)double ==在这里查看运营商

我建议为 cpp 阅读一本好书,并在此过程中变得更好。

如果您想知道,这是您的程序的工作版本


推荐阅读