c++ - 为什么我得到的是零?

标签 c++ math format zero

我对 C++ 有点陌生,我正在编写这个小程序来计算电影票的总额。

#include<iostream>
#include<string>
#include<iomanip>
#include<cmath>

using namespace std;

int adultTick, childTick;
const int aPrice = 14;
const int cPrice = 10;
float rate() {
    const double RATE = .20;
    return RATE;
}

double grossTotal = (aPrice * adultTick) + (cPrice * childTick);
int main() {

    cout << "Box Office Earnings Calculator ....\n" << endl;
    cout << "Please Enter the Name of the Movie: ";
    string movie_name;

    getline(cin, movie_name);


    cout << endl << "   \"   \"   " << "adult tickets sold: ";
    cin >> adultTick;

    cout << "   \"   \"   " << "child tickets sold: ";
    cin >> childTick;

    cout << endl << setw(10) << left << "Movie Title: " << setw(20) << right << " \" " << movie_name << " \" " << endl;
    cout << setw(10) << left << "Adult Tickets Sold: " << setw(20) << right << adultTick << endl;
    cout << setw(10) << left << "Child Tickets Sold: " << setw(20) << right << childTick << endl;
    cout << setw(10) << left << "Gross Box Office Profit: " << setw(20) << right << "$ " << grossTotal;


}

最后,程序应该在哪里显示总数?我认为算术是正确的,但我不明白为什么它不断显示零?我做错了什么? 如果我不为算术“grossTotal”创建变量,它会起作用,但我必须使用“setprecision”和“fixed”函数进行进一步格式化。

最佳答案

main 中的代码不会改变 grossTotal

声明

double grossTotal = (aPrice * adultTick) + (cPrice * childTick);

… 创建一个具有指定初始值的变量 grossTotal。它不声明这些变量的值之间的关系。

在初始化器表达式(= 的右边)被求值时 adultTickchildTick 为零,因为作为命名空间范围变量它们已被零初始化。

关于c++ - 为什么我得到的是零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682743/

相关文章:

java - C# ServiceStack 和 Java 之间的日期时间格式

c++ - 将初始化列表与从空基类继承的结构一起使用

c++ - 使用位数组?

c++ - 抓取 8 字节字的高 4 字节

c++ - 如果没有加入则中断线程

给定半径为1.00的圆坐标的java数学计算

math - 如何在brainfuck中读取多位数字

javascript - 将 slider 线性值转换为指数

c++ - 将秒(时钟)转换为十进制格式

Android软键盘首先显示数字 View