c/c++语言开发共享开始C程序

我正在使用哈佛大学的在线CS50课程开始学习一些问题。 我得到了正常工作的问题,但我想知道是否有更清洁或更好的方法让程序工作。

该程序的目标是打印由哈希标记和空格字符组成的右对齐金字塔。 任何关于风格或技巧的指导都将非常受欢迎。

/* Creating the mario program, whose goal is to create a * pyramid by accepting input from the user to get the * height then aligning the pyrimid to the right. * */ #include  #include  int main(void) { // get user input and set to variable printf("Height: "); int height = GetInt(); int i, j, k; for(i = 1 ; i  (i-1); k--) { printf("%c", ' '); } // create n+1 hash tags for(j = 0; j < (i+1); j++) { printf("#"); } printf("n"); } return 0; } 

    我假设更清洁你的意思是“漂亮和漂亮”。

    这看起来很漂亮:

     #include  #include  int main(void) { // get user input and set to variable printf("Height: "); int height = GetInt(); int hm2 = height - 2; int j, k; for(int i = 1 ; i < height; i++) { // create n-1 spaces for(k = hm2; k > (i-1); k--) printf("%c", ' '); // create n+1 hash tags for(j = 0; j < (i+1); j++) printf("#"); printf("n"); } return 0; } 

    但是,不要过于担心你的代码。 虽然如果你和别人一起工作,或者你自己真的很好,那就太好了。 你的例子很好看。

    现在, 优化方面,这是值得担心的事情。 请记住,过多的优化可能会破坏您的程序。

    供大家考虑:这就是“所有风格,没有可读性”的样子:)

     i = 0; while (i++ < height*height) printf ("%c%s", (i-1)/height < height-(i-1)%height-1 ? ' ' : '#', i % height ? "" : "n"); 

    如果不运行它,几乎不可能看到代码的作用。 如果要进行后续练习,很难重新编写forms,比如说,一个平等的金字塔。 我可能会抛弃它,然后重新开始基础知识,然后再将它再连接成一个像这样的小怪物。


    (后来)总是将i++放在最后,所以两次(i-1)被交易进行稍微复杂的行尾测试:

     i = 0; do printf ("%c%s", i/height < height-i%height-1 ? ' ' : '#', i % height==height-1 ? "n" : ""); while (++i < height*height); 

    我认为通过更干净,更好的方式,你的意思是成为一个完美形状的直角三角金字塔。
    为此,你应该这样做
    更改

     printf("Height: "); 

     printf("Height: nn"); 

     for(i = 1 ; i < height; i++) 

     for(i = 0 ; i < height; i++) 

    并查看示例输出 。

    这是一个建议:

     #include  #include  int main(void) { //initialize variables int height, hm2, j, k, i; printf("Height: n"); // Get user input height = GetInt(); hm2 = height - 1; for(i = 0; i < height; i++) { // create n spaces for(k = hm2; k > i; k--) printf("%c", ' '); // create n+1 hash tags for(j = 0; j < i+1; j++) printf("#"); printf("n"); } return 0; } 

    如果用户为高度输入5,则结果为:

     Height: # ## ### #### ##### 

    我在这个版本的代码中考虑了几件事:

    - 在C中,最好将所有变量分别声明给它们赋值并稍后赋值。 如果要在for循环中声明和赋值,某些编译器可能会出现此错误:“error:'for'循环初始声明仅允许在C99模式下”。 这些变化与我提供的内容一起考虑。

     //initialize variables int height, hm2, j, k, i; 

    我在这里添加了换行符

     printf("Height: n"); 

    - 而不是hm2 = height - 2我改为:

     hm2 = height - 1; 

    -First循环,现在我们给出ia值并将其设置为0以满足所做的其他更改:

     for(i = 0; i < height; i++) { 

    - 对于创建n个空格的循环,我将其更改为:

     for(k = hm2; k > i; k--) 

    - 最后一个for循环中最后删除的括号(在这种情况下不需要):

     for(j = 0; j < i+1; j++) 

    干杯

      以上就是c/c++开发分享开始C程序相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/541872.html

      (0)
      上一篇 2021年1月4日
      下一篇 2021年1月5日

      精彩推荐