printing a square with diagonals

前端 未结 4 1353
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 07:44

I want to print this if the user typed in for example 2:

+---+ 
|\\ /|
| X |
|/ \\|
+---+

It\'s a square with a size of 2n+1 for each side of i

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 08:21

    Homework is an exploration.

    You are trying to print an object that will have a number of decisions. You need to code for each one. Simple code for this might try the approach of 'print all the characters in a square, deciding what each should be.' That's your approach so far. Next you need to write if statements and correctly answer do I print '+', '-', '|', '\', '/', 'X', or ' '?

    You need to think about each character in order. For example, your first test, if (i == 0 && (j == 0 || j == size * 2)), but you need to expand it to get the '+' on the last line as well.

    One base idea is to first get something working. I suggest you start with your code and add items as you go. Here is an outline with '+' working:

    for (int i = 0;i < ((size * 2) + 1);i++){
        for (int j = 0; j < ((size * 2) + 1);j++){
            if ((i == 0 || i == size * 2) && (j == 0 || j == size * 2)){
                printf("+");
            }
            // more else if for '-', etc.
            else {
                printf(" ");
            }
        }
    }
    

    Once you have it printing the '+' at the four corners of a square, add the logic for each other charcter, checking that you get a square with the '-', '_', etc., correct.

    One other point is that there are other ways to do the problem, and you should explore how some seem less error prone than others. For example, if you change your outline to:

    int last = size * 2
    for (int i = 0; i < last + 1; i++){
        for (int j = 0; j < last + 1; j++){
            if ((i == 0 || i == last) && (j == 0 || j == last) {
               ...
    

    you may find that eliminating repetition and parenthesis makes it less error prone. Notice or keep track of the errors you make.

提交回复
热议问题