C++作业求助:如何实现横竖尺寸一致的指定地板图案输出
Fixing Your Floor Pattern C++ Code
Hey there! Let's work through your code to get that floor pattern right—with consistent horizontal/vertical dimensions and correct output. I'll break down the issues in your current code, share a revised version, and give you some optimization tips too.
Issues in Your Current Code
- Duplicate Condition Check: Your second
else if (i%2 != 0)is identical to the firstifcondition. That means even-numbered rows will never usearray2—you should useelseorelse if (i%2 == 0)instead. - Array Out-of-Bounds Risk:
array1andarray2only have 4 elements (indices 0-3), but your inner loop runsj <= n. Ifn > 3, this will access memory outside the arrays, causing undefined behavior. - Early Program Exit: You placed
return 0;inside the outerforloop. This makes the program exit after printing just the first row, instead of allnrows. - Mismatched Dimensions: Your inner loop prints
n+1characters per row, but you're only printingnrows—this breaks the "equal horizontal/vertical size" requirement.
Revised Working Code
This version fixes all the above issues, adds character looping for when n > 4, and ensures consistent dimensions:
#include <iostream> using namespace std; int main() { int n; // Use char arrays since we're dealing with single characters constexpr char oddRowChars[4] = {'O', '>', 'X', '<'}; constexpr char evenRowChars[4] = {'v', '/', '^', '\\'}; // Escape backslash cin >> n; for (int row = 1; row <= n; row++) { if (row % 2 != 0) { // Print n characters, looping through oddRowChars for (int col = 0; col < n; col++) { cout << oddRowChars[col % 4]; } } else { // Print n characters, looping through evenRowChars for (int col = 0; col < n; col++) { cout << evenRowChars[col % 4]; } } cout << '\n'; // Use '\n' instead of endl for faster output } return 0; }
Is Using Arrays Necessary?
Absolutely—arrays are a great choice here! They organize your pattern characters into clear, maintainable groups. Without arrays, you'd have to use messy conditional logic (like switch statements) to pick each character, which would make the code harder to read and modify.
Extra Optimization Tips
- Avoid
#include<bits/stdc++.h>: It includes every standard library header, which bloats your code. Stick to only what you need—here, just#include <iostream>. - Use
constexpr: Marking the character arrays asconstexprlets the compiler resolve them at compile time, making your program slightly more efficient. - Simplify Row Checks: You could start your row loop at 0 instead of 1, making the parity check more concise:
if (row % 2 == 0)for even rows. - Single-Line Row Selection: Use a ternary operator to pick the current row's character set in one line:
const char* currentChars = (row % 2 != 0) ? oddRowChars : evenRowChars;
内容的提问来源于stack exchange,提问作者nguyen
相关产品推荐
相关产品推荐

