N
,判斷是否為 9 的倍數及輸出 nine-degree
N
直到 0 (最大到 1000 位)nine-degree
nine-degree
= 2N is a multiple of 9 and has 9-degree D.
N is not a multiple of 9.
while
迴圈重複輸入 N
,直到讀進 0;因為數字可能很大,用字串方式讀入存到字元陣列中
int main(){
char N[1001] = {0};
while(scanf("%s", N)){
if(N[0] == '0' && strlen(N) == 1){
break;
}
else{
...
}
}
return 0;
}
main()
處理好輸出格式
printf("%s ", N);
int D = degree(N);
if(D){
printf("is a multiple of 9 and has 9-degree %d.", D);
}
else{
printf("is not a multiple of 9.");
}
printf("\n");
for
迴圈遍歷字元計算總和,只要 % 9 == 0
代表即為 9 的倍數,並更新次數;再透過 sprintf()
這個神奇的函式把整數轉回字元陣列繼續計算
int degree(char *str){
int i;
int multiple, D = 0;
if(strlen(str) == 1 && str[0] == '9'){
return 1;
}
while(strlen(str) >= 2){
multiple = 0;
for(i = 0; i < strlen(str); i++){
multiple = multiple + str[i] - '0';
}
if(multiple % 9 == 0){
D++;
}
sprintf(str, "%d", multiple);
}
return D;
}
#include<stdio.h>
#include<string.h>
int degree(char *str){
int i;
int multiple, D = 0;
if(strlen(str) == 1 && str[0] == '9'){
return 1;
}
while(strlen(str) >= 2){
multiple = 0;
for(i = 0; i < strlen(str); i++){
multiple = multiple + str[i] - '0';
}
if(multiple % 9 == 0){
D++;
}
sprintf(str, "%d", multiple);
}
return D;
}
int main(){
char N[1001] = {0};
while(scanf("%s", N)){
if(N[0] == '0' && strlen(N) == 1){
break;
}
else{
printf("%s ", N);
int D = degree(N);
if(D){
printf("is a multiple of 9 and has 9-degree %d.", D);
}
else{
printf("is not a multiple of 9.");
}
printf("\n");
}
memset(N, 0, sizeof(N));
}
return 0;
}