4.31 個度我諗極都諗唔明點樣
第一行space4下之後一粒星
第二行space3下之後三粒星
第三行space2下之後五粒星
第四行space1下之後七粒星
第五行space0下之後九粒星
space就係本身4 係咁-1直到0啦
星就由1開始係咁+2變到9啦
我想將佢複雜簡單化佢
同埋 第二條個度 明明我人手計極都係2548/2650 點解會出2550
明明初初個num = 2 跟住就 num= num+2 就 num=4
跟住sum本身=0 sum=sum+num 即係 sum= 0 + 4 就 sum=4
之後就 num = 4 then num=num+2 then num=6
sum=4+6 so = 10
如此類推
loop到去num= 98 then num=num+2 就 num=100
跟住sum=sum+num sum=2448+100 sum=2548
我覺得照計LOOP到SUM=2548+102=2650
到底點解答案又會係2550既
認真求教
問題一
4.31 (Diamond Printing Program) Write a program that prints the following diamond shape. You may use printf either a single asterisk (*) or a single blank. Maximize your use of repetition (with nested for statements) and minimize the number of printf statements.
OUTPUT如下
*
***
*****
*******
*********
*******
*****
***
*
答案如下
- #include <stdio.h>
- int main( void )
- {
- int line;
- int space;
- int asterisk;
- for ( line = 1; line <= 9; line += 2) {
- for ( space = ( 9 - line ) / 2; space > 0; space-- ) {
- printf( " " );
- }
-
- for ( asterisk = 1; asterisk <= line; asterisk++ ) {
- printf( "*");
- }
-
- printf( "\n" );
- }
-
- for ( line = 7; line >= 0; line -= 2 ) {
- for ( space = ( 9 - line ) / 2; space > 0; space--) {
- printf( " " );
- }
-
- for ( asterisk = 1; asterisk <= line; asterisk++ ) {
- printf( "*" );
- }
-
- printf( "\n" );
- }
-
- return 0;
- }
第二條
- /* Fig. 4.5: fig04_05.c
- Summation with for */
- #include <stdio.h>
-
- /* function main begins program execution */
- int main()
- {
- int sum = 0; /* initialize sum */
- int number; /* number to be added to sum */
-
- for ( number = 2; number <= 100; number += 2 ) {
- sum += number; /* add number to sum */
- } /* end for */
-
- printf( "Sum is %d\n", sum ); /* output sum */
-
- return 0; /* indicate program ended successfully */
-
- } /* end function main */
OUTPUT如下
Sum is 2550
[ 本文被星淺在2010-10-19 08:29重新編輯 ]