C++ cin 无论用户输入什么,都返回 0 作为整数

C++ cin returns 0 for integer no matter what the user inputs

本文关键字:返回 整数 什么 cin 用户 输入 C++      更新时间:2023-10-16

无论 cin 如何,它都会继续输出 0 以获得分数。为什么?我尝试返回"返回 0;",但仍然没有去:/

#include "stdafx.h"
#include <iostream>
using namespace std;
// Variables
int enemiesKilled;
const int KILLS = 150;
int score = enemiesKilled * KILLS; 
int main()
{
    cout << "How many enemies did you kill?" << endl;
    cin >> enemiesKilled;
    cout << "Your score: " << score << endl;
    return 0;
}
您需要在

用户输入输入后执行乘法:

int main()
{
    cout << "How many enemies did you kill?" << endl;
    cin >> enemiesKilled;
    int score = enemiesKilled * KILLS;
    cout << "Your score: " << score << endl;
    return 0;
}

在线查看: ideone

您需要在用户输入数字重新计算score

cin >> enemiesKilled;
score = enemiesKilled * KILLS; // <-- Put the calculation here!!
cout << "Your score: " << score << endl;

程序启动时int enemiesKilled;初始化为 0。

同时计算int score = enemiesKilled * KILLS;。 由于enemiesKilled为 0,因此它也为 0。

如其他答案中所述,您需要在运行时计算score