算法競賽入門經典(第2版)
第2章 循環結構程序設計
2.5 分數化小數,注意進位等問題
#include "stdio.h"
#include "math.h"
int main(){
int a,b,c;
int count=0;
while(scanf("%d",&a)==1){
scanf("%d %d",&b,&c);
if(a==0&&b==0&&c==0){
break;
}
count++;
float x = (float)a/b; //x爲實際值
int x1 = x;
printf("Case %d:",count);
int x2[c+2];
x2[0]=0;
float p = (float)a-x1*b; //去掉整數部分
for(int i=1;i<c+2;i++){ //計算小數點後的位數
p=p*10;
x2[i]=p/b;
p=p-x2[i]*b;
}
//處理進位
if(x2[c+1]>=5){
for(int i=c;i>=0;i--){
x2[i]++;
if(x2[i]<10){ //不影響前一位
break;
}
else{
x2[i]-=10; //滿十進一
}
}
}
if(x2[0]) printf("%d.",x1+1); //處理整數的進位 ,x2[0]用來保存x是否會進位到整數
else printf("%d.",x1);
for(int i=1;i<=c;i++){
printf("%d",x2[i]);
}
printf("\n");
}
return 0;
}
2.6排列(順便上傳一下)
#include "stdio.h"
int main(){
for(int abc=123;abc<321;abc++){
int def = abc*2;
int ghi = abc*3;
int a = abc/100;
int b = (abc%100)/10;
int c = abc%10;
int d = def/100;
int e = (def%100)/10;
int f = def%10;
int g = ghi/100;
int h = (ghi%100)/10;
int i = ghi%10;
if(a!=b&&a!=c&&a!=d&&a!=e&&a!=f&&a!=g&&a!=h&&a!=i){
if(b!=c&&b!=d&&b!=e&&b!=f&&b!=g&&b!=h&&b!=i){
if(c!=d&&c!=e&&c!=f&&c!=g&&c!=h&&c!=i){
if(d!=e&&d!=f&&d!=g&&d!=h&&d!=i){
if(e!=f&&e!=g&&e!=h&&e!=i){
if(f!=g&&f!=h&&f!=i){
if(g!=h&&g!=i){
if(h!=i){
printf("%d %d %d\n",abc,def,ghi);
}
}
}
}
}
}
}
}
}
return 0;
}