c++ - “SalesTaxPct”未在此范围内声明

标签 c++

我是 C++ 新手。我在值(value)传递方面苦苦挣扎,没有人能以我能理解的方式向我解释我做错了什么。我知道这是我的错,但我正在寻求有关我的代码的帮助。请帮助!

#include <iostream>
using namespace std;

double getValues();
double getSalesTax(double SalesTaxPct);
double gettotal_price(double base, double opt);
void PrintFinal(double base,double opt,double SalesTaxPct);

// function to control all other functions
int main()
{
    getValues();
    getSalesTax(SalesTaxPct);
    PrintFinal(base,pt,SalesTaxPct);
}

// function to calculate sales tax percent into decimal 
double getSalesTax( double SalesTaxPct )    

{
    double SalesTax;

    SalesTax = SalesTaxPct / 100;

    return SalesTax;
}



// function to find total
double gettotal_price(double base, double opt, double SalesTax)

{

    return = (base + opt) * (1 + SalesTax);


}


// function to show user all values input and also total
void PrintFinal(double base, double opt, double SalesTaxPct)

{
    cout << "Base vehicle price: $" << base << endl;

    cout << "Options Price: $" << opt << endl;

    cout << "Sales tax pct: " << SalesTaxPct << "%" << endl;

    cout << "Total vehicle price: $" << gettotal_price(double base, double opt, double SalesTax) << endl;

}


// function to get input values
void getValues()
{
    double base, double opt, double SalesTaxPct;

    cout << "Enter a base vehicle price: " << endl;
    cin >> base;

    cout << "Enter options price: " << endl;
    cin >> opt;

    cout << "Enter a sales tax percent: " << endl;
    cin >> SalesTaxPct;


}

最佳答案

当您在 main 中时,让我们回顾一下程序看到的内容:

int main()
{
    getValues();
    getSalesTax(SalesTaxPct);
    PrintFinal(base,pt,SalesTaxPct);
}

此时您的程序唯一知道的变量是:getValues()getSalesTax()gettotal_price()PrintFinal()。该警告告诉您,在您的程序的这一点上,SalesTaxPct 尚未声明,并且查看我们程序知道的变量/函数列表,我们确实看到了 SalesTaxPct 不在列表中。我们期望 SalesTaxPct 的值来自哪里?

看起来它来自函数 getValues,我们从用户输入中获取它。然而,任何时候你有 { ... } ,大括号里面的东西不能从外面访问。因此,SalesTaxPct 仅在函数 getValues 的“范围内”。如果您希望它可以在该函数之外访问(您这样做),则需要稍微改变一下。

int main()
{
    double base;
    double opt;
    double SalesTaxPct;
    getValues(base, opt, SalesTaxPct);
    getSalesTax(SalesTaxPct);
    PrintFinal(base, opt, SalesTaxPct);
}

现在,当我们在 main 中需要它们时,我们所有的变量仍然存在。但是,这里仍然存在问题。我们希望传递给 getValues 的更改能够更改 main 中的变量。这意味着我们不能“按值”传递,因为那将首先制作一个拷贝,然后更改这些拷贝(不是我们想要的)。相反,我们需要说明我们所做的更改需要以某种方式从函数返回:

void getValues(double & base, double & opt, double & SalesTaxPct);

那里的那个小 & 意味着我们不是复制并更改该拷贝,而是告诉函数对我们直接传入的变量进行操作。这称为“按引用传递”。

您的代码的其他部分也存在一些类似的问题,但现在您或许可以想出解决方法。

关于c++ - “SalesTaxPct”未在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10337166/

相关文章:

c++ - 类中的重载方法(arduino)

c++ - 用模板实现派生类

c++ - 它没有像预期的那样 sleep

c++ - 查找 cpp_int 二进制长度的简单方法

c++ - 我什么时候应该在 C++ 中使用我自己的销毁函数?

c++ - libzip 与 zip_source_buffer 会导致数据损坏和/或段错误

c++ - 在 arduino 上使用 strncat 方法输出错误值

c++ - `*this` 外部成员函数体?

c++ - 检查字符串是否包含 vector<string> 值的有效方法?

c++ - 使用#ifndef 时具体定义了什么