c++ - 未在此范围错误中声明

标签 c++

我想让这个程序计算工资总额,但它输出错误。

#include<stdio.h>

int main() {
    float base-salary = 1500.00;
    float bonus-rate = 200.00;
    float commission-rate = quantity * 2/100;
    int quantity;
    float Price;
    float Gross-salary;

    printf("Enter quantity of computers sold\n");
    scanf("%d",&quantity);
    printf("Enter Price of computers sold\n");
    scanf("%f",&Price);

    Gross-salary = base-salary + (quantity * bonus-rate) + (quantity * Price) * commission-rate;
    printf("Gross salary equals :%f",Gross-salary);


    //Gross salary = base salary + (quantity * bonus rate) + (quantity * Price) * commission rate


}

它吐出这些错误。

5 13 Documents\Untitled10.cpp [Error] expected initializer before '-' token 16 2 Documents\Untitled10.cpp [Error] 'Gross' was not declared in this scope 16 2 Documents\Untitled10.cpp [Error] 'base' was not declared in this scope 16 2 Documents\Untitled10.cpp [Error] 'salary' was not declared in this scope 16 2 Documents\Untitled10.cpp [Error] 'bonus' was not declared in this scope 16 2 Documents\Untitled10.cpp [Error] 'rate' was not declared in this scope 16 2 Documents\Untitled10.cpp [Error] 'commission' was not declared in this scope

最佳答案

您不能在 C++ 标识符名称中使用 - 破折号。切换为下划线。

引用http://en.cppreference.com/w/cpp/language/identifiers :

An identifier is an arbitrarily long sequence of digits, underscores, lowercase and uppercase Latin letters, and most Unicode characters (disallowed are control characters and characters in the basic source character set). A valid identifier must begin with a non-digit character (Latin letter, underscore, or Unicode non-digit character). Identifiers are case-sensitive (lowercase and uppercase letters are distinct), and every character is significant.

此外,在计算中使用浮点除法,而不是整数。

float commission-rate = quantity * 2/100;

由于数量是int,所以会进行整数除法,你只会得到结果的截断部分。这样做:

float commission_rate = quantity * 2/100.f;

在声明变量之前使用变量还有另一个错误:

float commission_rate = quantity * 2/100;
int quantity;

数量未声明,因此不能在第 1 行中使用。交换这些语句。另外,请注意 C++ 不是一种符号数学语言。在评估表达式时获取变量值。这是一个常见的初学者错误,首先声明一个公式,然后初始化它包含的变量。因此,第 1 行必须移到输入部分下方。

您的固定代码可能如下所示:

const float base_salary = 1500.f;
const float bonus_rate = 200.f;
int quantity;
float price;
float gross_salary;

printf("Enter quantity of computers sold\n");
scanf("%d",&quantity);
printf("Enter Price of computers sold\n");
scanf("%f",&price);

const float commission_rate = quantity * 2/100.f;
const gross_salary = base_salary + quantity * bonus_rate + \
                     quantity * price * commission_rate;
printf("Gross salary equals :%f",gross_salary);

关于c++ - 未在此范围错误中声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35668985/

相关文章:

c++ - 供应商是否将 new 和 malloc 实现为小对象分配器?

c# - ZeroMQ PUB/SUB 模式与多线程轮询取消

c++ - 指向 vector 元素的空指针

c++ - Makefile 错误导致对符号 'GOMP_parallel@@GOMP_4.0' 的 undefined reference

c++ - 如何将 TCHAR 数组与字符串连接起来?

c++ - 在函数 C++ 中使用字符串数组

c++ - gdb 无法进入 printf

C++ Winsock 2 题

c++ - 在 C++ 流中检索标志

c++ - 你需要只读锁定吗