獲取你自己的
網站
×
更改方向
更改主題,深色/淺色
前往 Spaces
#include <iostream> using namespace std; int main() { // We put "1" to indicate there is a ship. bool ships[4][4] = { { 0, 1, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }; // Keep track of how many hits the player has and how many turns they have played in these variables int hits = 0; int numberOfTurns = 0; // Allow the player to keep going until they have hit all four ships while (hits < 4) { int row, column; cout << "Selecting coordinates\n"; // Ask the player for a row cout << "Choose a row number between 0 and 3: "; cin >> row; // Ask the player for a column cout << "Choose a column number between 0 and 3: "; cin >> column; // Check if a ship exists in those coordinates if (ships[row][column]) { // If the player hit a ship, remove it by setting the value to zero. ships[row][column] = 0; // Increase the hit counter hits++; // Tell the player that they have hit a ship and how many ships are left cout << "Hit! " << (4-hits) << " left.\n\n"; } else { // Tell the player that they missed cout << "Miss\n\n"; } // Count how many turns the player has taken numberOfTurns++; } cout << "Victory!\n"; cout << "You won in " << numberOfTurns << " turns"; return 0; }
選擇座標
選擇一個介於 0 和 3 之間的行號:2
選擇一個介於 0 和 3 之間的列號:1
未命中
選擇座標
選擇一個介於 0 和 3 之間的行號:2
選擇一個介於 0 和 3 之間的列號:2
命中!還剩 3 個。
選擇座標
選擇一個介於 0 和 3 之間的行號:2
選擇一個介於 0 和 3 之間的列號:2
未命中
選擇座標
選擇一個介於 0 和 3 之間的行號:3
選擇一個介於 0 和 3 之間的列號:2
命中!還剩 2 個。
選擇座標
選擇一個介於 0 和 3 之間的行號:0
選擇一個介於 0 和 3 之間的列號:2
命中!還剩 1 個。
選擇座標
選擇一個介於 0 和 3 之間的行號:0
選擇一個介於 0 和 3 之間的列號:0
未命中
選擇座標
選擇一個介於 0 和 3 之間的行號:0
選擇一個介於 0 和 3 之間的列號:1
命中!還剩 0 個。
勝利!
您在 7 回合內獲勝
程序返回 0 (0x0) 執行時間:24.994 秒