[英]c++ wont take absolute value of a number
我在 c++ 中創建了一個井字游戲 AI。我嘗試添加代碼以將 X 添加到玩家放置它的位置,但是當我運行它時,它給了我一個與第 37 行相關的錯誤。有一個表達式可以簡單地轉換一組坐標成一個數字。 重新排列代碼給了我另一個錯誤。 該錯誤可能與我要求絕對值的方式有關。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<string>> Board
{
{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}
};
string playerInput;
bool hasMoved = false;
bool run = true;
while(run) {
//Prints Tic Tac Toe board to the screen
for(int h = 0; h < Board.size();h++){
cout << " ";
for(int d = 0; d < Board[h].size();d++){
cout << Board[h][d];
if(d < Board[h].size() - 1){ cout <<"||"; }
}
if(h < Board.size() - 1){ cout << "\n---------\n"; }
}
cout << "\n choose a number 1-9 to place an X: ";
cin >> playerInput;
hasMoved = false;
while(!hasMoved){
for(int h = 0; h < Board.size();h++){
for(int d = 0; d < Board[h].size();d++){
if(Board[h].size() * abs(h - Board[h].size() + 1) + d == playerInput && Board[h][d] == " ") {
Board[h][d] = "X";
hasMoved = true;
}
}
}
if(!hasMoved){
cout << "\n choose a number 1-9 to place an X: ";
cin >> playerInput;
}
}
}
}
這並不像您期望的那樣工作:
abs(h - Board[h].size() + 1)
對vector::size()
的調用返回一個size_t
值,您要從int
值中減去該值。 根據 算術轉換規則, int
將被轉換為unsigned
。
所以你所擁有的是一個無符號類型,你的減法將“低於”零。 結果將是一個非常大的數字。
修正方程的一種方法是將結果轉換為 int:
abs(h - static_cast<int>(Board[h].size()) + 1)
但在這種情況下,簡單地調整方程不換行會更好:
Board[h].size() - h - 1
編譯代碼時我看到的第一個錯誤是:
temp.cpp:37:42: error: call to 'abs' is ambiguous
...即編譯器有多個版本的abs
function 可以調用,但它不知道應該使用哪一個:
note: candidate function
inline _LIBCPP_INLINE_VISIBILITY long abs(long __x)
^
note: candidate function
inline _LIBCPP_INLINE_VISIBILITY long long abs(long long __x)
^
note: candidate function
inline _LIBCPP_INLINE_VISIBILITY float abs(float __lcpp_x)
^
note: candidate function
inline _LIBCPP_INLINE_VISIBILITY double abs(double __lcpp_x)
^
note: candidate function
abs(long double __lcpp_x)
...這很容易修復,我們只需將參數轉換為abs
明確處理的類型之一:
abs(static_cast<long>(h - Board[h].size() + 1))
第二個錯誤是這樣的:
temp.cpp:37:82: error: invalid operands to binary expression ('unsigned long' and 'std::string' (aka 'basic_string<char>'))
... 是因為您試圖將字符串與整數類型進行比較,這是沒有意義的。 大概您想先將字符串轉換為 integer,這樣您就可以比較它:
cin >> playerInput;
const int playerInputInt = atoi(playerInput.c_str());
[...]
if(Board[h].size() * abs(static_cast<long>(h - Board[h].size() + 1)) + d == playerInputInt && Board[h][d] == " ") {...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.