C++中字符数组的输入 财富值2

2016-10-15 23:53发布

如上图,红线框起来的部分,为什么字符数组的输入放到里面出来的结果是不正确的,而按照下面的方法,放到循环的外面去输入运行结果是正确的?

正确放法图
下面放完整代码:

#include<iostream> #include<stdio.h> using namespace std; int main(){         char n[100] = { 0 };         int sum = 0;         cin>>n;         int i, number, mask = 1;         for (i = 0; n[i] != 0; i++) {             sum += (int)n[i] - 48;         }         int a = sum;         while (a>9){             a /= 10;             mask *= 10;         }          do{             number = sum / mask;             sum %= mask;             mask /= 10;             switch (number){             case 0:printf("ling"); break;             case 1:printf("yi"); break;             case 2:printf("er"); break;             case 3:printf("san"); break;             case 4:printf("si"); break;             case 5:printf("wu"); break;             case 6:printf("liu"); break;             case 7:printf("qi"); break;             case 8:printf("ba"); break;             case 9:printf("jiu"); break;             }             if (mask>0){                 printf(" ");             }         } while (mask>0);      system("pause");     return 0; }  这个题的题目 ![图片描述][3] 

我的错误的代码:

#include<iostream> #include<stdio.h> using namespace std; int main(){     char n[100] = { 0 };     int sum = 0, number, mask = 1;     for (int i = 0; i != 0; i++){         cin >> n[i];         sum = sum + (int)n[i] - 48;     }     int a = sum;     while (a > 9){         a = a / 10;         mask = mask * 10;     }     do{         number = sum / mask;         sum = sum % mask;         mask = mask / 10;         switch (number){         case 0:printf("ling");             break;         case 1:printf("yi");             break;         case 2:printf("er");             break;         case 3:printf("san");             break;         case 4:printf("si");             break;         case 5:printf("wu");             break;         case 6:printf("liu");             break;         case 7:printf("qi");             break;         case 8:printf("ba");             break;         case 9:printf("jiu");             break;         default:break;             if (mask > 0){                 printf(" ");             }         }      } while (mask > 0);     system("pause");     return 0; } 

为什么字符数组的输入不放到循环里面呢?而且放到里面的运行结果是错误的。