如何在C ++中的if
循环中使用else
和while
语句?我不确定我做错了什么。我认为它可能与float
变量有关,或者可能是代码在while
循环之后的位置。
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
float FEnemyPos[3] = { 15.1f, 30.1f, 50.1f };
char cEnemyTypes[3][10] = { "Trolls", "skeletons", "Axemen" };
float fPlayerPos = 20;
float fPlayerMoves;
float Ftrolldistance;
float Fskeledistance;
float Faxemendistance;
float fValueEntered = 0;
std::cout << "Please enter number \t";
while (fValueEntered != -99) {
std::cout << "Please enter number \t";
std::cin >> fPlayerMoves;
fValueEntered = fValueEntered + fPlayerMoves;
fPlayerPos = fPlayerMoves + fPlayerPos;//player position
std::cout << "value entered" << fValueEntered;
std::cout << "player pos" << fPlayerPos;
Ftrolldistance = FEnemyPos[1] - fPlayerPos;
Fskeledistance = FEnemyPos[2] - fPlayerPos;
Faxemendistance = FEnemyPos[3] - fPlayerPos;
std::cout << "troll distance " << Ftrolldistance;
if (Ftrolldistance <= 2 && Ftrolldistance >= -2) //if troll is less <2 and more then -2,
{
std::cout << "trolls are close";//print you are in danger
}
else if (Fskeledistance <= 2 && Fskeledistance >= -2)//if skelle is less <2 and more then - 2,
{
std::cout << "skelle are close ";//print you are in danger
}
else if (Faxemandistance <= 2 && Faxemendistance >= -2)//if axemen is less <2 and more then - 2,
{
std::cout << "axemen are close";//print you are in danger
}
else
{
std::cout << "you are safe for now \t";//else print you are safe
}
}
}
答案 0 :(得分:1)
代码太多,但我发现了一个问题...... 你的阵列有3个成员。
float FEnemyPos[3] = { 15.1f, 30.1f, 50.1f };
但是你从索引1开始使用它并且上升到索引3。
Ftrolldistance = FEnemyPos[1] - fPlayerPos;
Fskeledistance = FEnemyPos[2] - fPlayerPos;
Faxemendistance = FEnemyPos[3] - fPlayerPos;
您应该像下面一样进行更改,因为您在索引3上的数组中没有任何内容,当您尝试访问它时,它是无效的内存访问。
Ftrolldistance = FEnemyPos[0] - fPlayerPos;
Fskeledistance = FEnemyPos[1] - fPlayerPos;
Faxemendistance = FEnemyPos[2] - fPlayerPos;
答案 1 :(得分:0)
你可以缩短代码!
主要问题是索引始终以0
开头答案 2 :(得分:-1)
差代码质量,您听说过代码风格吗? 评论? 你运行过代码吗? 在编写了一段代码之后,我会给你一个提示,然后编译从下到上阅读它会帮助你检测这样的问题: 数组的第一个索引始终为0 !!! 所以数组中的第3个值为2 <索引 =&GT;技术上如此:
Faxemendistance = FEnemyPos[3] - fPlayerPos;
会产生错误。要修复它,你必须写:
Ftrolldistance = FEnemyPos[0] - fPlayerPos;
Fskeledistance = FEnemyPos[1] - fPlayerPos;
Faxemendistance = FEnemyPos[2] - fPlayerPos;