我有一个简单的程序,但它运行得很奇怪。基本上代码运行正常但是当行开头的编号发挥作用时,int x ++显示与第一行相同的数字然后继续。为什么会这样?
代码:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <string>
#include "logo.h"
int main()
{
SetConsoleTitle("plains.exe");
displayLogo();
int number;
int addTotal = 0;
int numbersEntered = 0;
std::cout << " [1] enter your first number: ";
std::cin >> number;
while (number != -1) {
addTotal = addTotal + number;
numbersEntered++;
std::cout << " [" << numbersEntered << "]" << " enter your next number or type '-1' to add them: ";
std::cin >> number;
}
if (number == -1) {
std::cout << " " << std::endl;
std::cout << " --------------------------------" << std::endl;
std::cout << " " << std::endl;
std::cout << " the sum of your numbers is " << addTotal << "." << std::endl;
std::cout << " you entered a total of " << numbersEntered << " numbers." << std::endl;
std::cout << " " << std::endl;
std::cout << " the average of your numbers is " << addTotal / numbersEntered << "." << std::endl;
std::cout << " " << std::endl;
}
return 0;
}
答案 0 :(得分:1)
您已将 <property>
<name>fs.hdfs.impl.disable.cache</name>
<value>true</value>
</property>
初始化为numbersEntered
。第一次通过0
循环时,while
会将其设置为numbersEntered++
。因此循环中的第一个提示包含1
。这与您在循环之前打印的内容相同:
[1]
所以你看两次std::cout << " [1] enter your first number: ";
。
要防止此重复,请在显示提示时将[1]
添加到变量:
1