1.编写一个程序,为所有从1~10之间的整数n生成并显示n和n²的表,确保能打印出正确的列标题。
1 // 2 // main.m 3 // LogXu 4 // 5 // Created by 许朕 on 15/2/9. 6 // Copyright (c) 2015年 com.example. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 int main(int argc, const char * argv[]) { 12 @autoreleasepool { 13 int n; 14 int product; 15 NSLog(@"table n table n²"); 16 NSLog(@"--------- -----------------"); 17 for (n=1; n<=10; n++) { 18 product=n*n; 19 NSLog(@"n=%2i n²=%i",n,product); 20 } 21 22 23 NSLog(@"Hello, World!"); 24 } 25 return 0; 26 }
2015-02-09 11:59:46.940 LogXu[3193:375201] table n table n² 2015-02-09 11:59:46.941 LogXu[3193:375201] --------- ----------------- 2015-02-09 11:59:46.941 LogXu[3193:375201] n= 1 n²=1 2015-02-09 11:59:46.941 LogXu[3193:375201] n= 2 n²=4 2015-02-09 11:59:46.942 LogXu[3193:375201] n= 3 n²=9 2015-02-09 11:59:46.942 LogXu[3193:375201] n= 4 n²=16 2015-02-09 11:59:46.942 LogXu[3193:375201] n= 5 n²=25 2015-02-09 11:59:46.942 LogXu[3193:375201] n= 6 n²=36 2015-02-09 11:59:46.942 LogXu[3193:375201] n= 7 n²=49 2015-02-09 11:59:46.942 LogXu[3193:375201] n= 8 n²=64 2015-02-09 11:59:46.942 LogXu[3193:375201] n= 9 n²=81 2015-02-09 11:59:46.943 LogXu[3193:375201] n=10 n²=100 2015-02-09 11:59:46.943 LogXu[3193:375201] Hello, World!
2.编写一个程序,生成并打印前10个整数的阶乘表。
1 // 2 // main.m 3 // LogXu 4 // 5 // Created by 许朕 on 15/2/9. 6 // Copyright (c) 2015年 com.example. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 int main(int argc, const char * argv[]) { 12 @autoreleasepool { 13 int n; 14 int factorial=1; 15 for (n=1; n<=10; n++) { 16 factorial*= n; 17 } 18 NSLog(@"n'factorial= %i",factorial); 19 NSLog(@"Hello, World!"); 20 } 21 return 0; 22 }
1 2015-02-09 12:09:47.990 LogXu[3311:382170] n'factorial= 3628800 2 2015-02-09 12:09:47.991 LogXu[3311:382170] Hello, World!
3.计算整数各位上数字的和。该程序可接收用户输入的任意整数。
1 // 2 // main.m 3 // LogXu 4 // 5 // Created by 许朕 on 15/2/9. 6 // Copyright (c) 2015年 com.example. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 int main(int argc, const char * argv[]) { 12 @autoreleasepool { 13 int n; 14 int right_number = 0; 15 int sum = 0; 16 NSLog(@"Please Input a Integer number:"); 17 scanf("%i",&n); 18 while (n!=0) { 19 right_number = n%10; 20 NSLog(@"%i",right_number); 21 n=n/10; 22 sum=sum+right_number; 23 } 24 NSLog(@"Sum= %i",sum); 25 NSLog(@"Hello, World!"); 26 } 27 return 0; 28 }
2015-02-09 13:23:44.918 LogXu[3459:396460] Please Input a Integer number: 2155 2015-02-09 13:23:48.334 LogXu[3459:396460] 5 2015-02-09 13:23:48.335 LogXu[3459:396460] 5 2015-02-09 13:23:48.335 LogXu[3459:396460] 1 2015-02-09 13:23:48.335 LogXu[3459:396460] 2 2015-02-09 13:23:48.335 LogXu[3459:396460] Sum= 13 2015-02-09 13:23:48.336 LogXu[3459:396460] Hello, World!