linux下的c语言入门-day4

来源:互联网 发布:java rectangle类 编辑:程序博客网 时间:2024/06/06 05:08

之前复习了以便循环的只是概念,还是打算把他给写出来。


for循环一般用于计算循环的次数,在该循环中控制变量的值在每次迭代时递增或递减指定的值i,知道到达某个最终值为止。


while循环只要给定的条件是true就继续执行。如果循环条件在循环语句一开始就是false的,循环语句就根本不执行。


do while循环类似于while循环,但其循环条件在循环语句块执行后检查。因此循环语句块至少会执行一次。


再次记录一下编程的规则:

1.开始编程之前,先规划好过程和计算的逻辑,将它写下来最好,采用流程图的形式。试着从侧面思考,这也许比直接的方法更好。


2.要理解运算符的优先级,以正确计算复杂的表达式。如果不能确定运算符的优先级,就应该使用括号,确保表达式完成预期的操作。


3.要有给程序加上注释的习惯,全面解释他的使用和操作。要假设这些注释是方便给别人阅读这些程序,并加以扩展。声明变量时应该说明他们的应用。


4.程序的可读性是最重要的。


5.使用缩进格式,留出适当的空位,不让太挤,可视化的表达出程序的结构。


这里最后有个simon游戏,但是始终无法让数字显示在屏幕上。但是整体的逻辑还是理解的

#include#include#include#include#includeint main(){char another_game = 'Y';bool correct = true;int counter = 0;int sequence_length = 0;int seed = 0;int number = 0;long now = 0;int time_taken = 0;int i =1;printf("\n To play simple simon, ");printf("watch the screen for a sequence of digits.");printf("\n Watch carefully, as the digits are only displayed for second!");printf("\n The computer will remove them, and then prompt you");printf("to enter the same sequence.");printf("\n When you do, you must put spaces between the digits.\n");printf("\n Good luck!\npress enter to play\n");scanf("%c", &another_game);do{correct = true;counter = 0;sequence_length = 2;time_taken = clock();while(correct){sequence_length += counter++%3 ==0;seed = time(NULL);now = clock();srand((int)seed);for(i = 1; i <= sequence_length; i++)printf("%d", rand() % 10);for( ; clock() - now < CLOCKS_PER_SEC; );printf("\r");for(i = 1; i <= sequence_length; i++)printf(" ");if(counter == 1)printf("\n Now you enter the sequence - do not forget the spaces\n");elseprintf("\r");srand(( int)seed);for(i =1; i <= sequence_length; i++){scanf("%d", &number);if(number != rand() % 10){correct = false;break;}}printf("%s\n", correct ? "Correct!" : "Wrong!");}time_taken = (clock() - time_taken) / CLOCKS_PER_SEC;printf("\n\n Your score is %d", --counter * 100  / time_taken);fflush(stdin);printf("\n Do you want to play again (y/n)? ");scanf("%c", &another_game);} while(toupper(another_game) == 'Y');return 0;}
很多函数都具有自己的头文件,不要忘记申明了。

下一站,数组~

0 0