VR引擎程序设计基础class3

135 阅读2分钟

1.练习

1.如果n为奇数,将n变为3n+1,否则,变成一半,若干次后,n都会为1,输出变换次数,输入3输出7

int i = 0;
int n = Convert.ToInt32(Console.ReadLine());
while (n!=1) {
    if (n%2==0){//能被2整除的偶数
        n = n / 2;
    }
    else{
        n = 3 * n + 1;
    }
    i++;
}
Console.WriteLine(i);

图片.png

2.保留三位小数

double x = 123.412142241;
Console.WriteLine(x.ToString("0.000"));

图片.png

3.打印水仙花数,即满足 153=1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3的三位数

int a, b, c;
for (int i = 100; i < 1000; i++)
{   
    c = i % 10;//求个位
    b = i / 10 % 10;//求十位
    a = i / 100 % 10;//求百位
    if (c*c*c+b*b*b+a*a*a==i)
    {
        Console.WriteLine(i);
    }
}

图片.png

4.球落地后,反弹高度减半,求第10次反弹多高?第10次落地时经过距离?

int n = 10;
double sum = 0;
double h = 100;//初始高度
for (int i = 0; i < n; i++)
{
    h /= 2;
    sum += h*3;//每一次下落到下一次反弹,总距离为反弹距离3倍
}
Console.WriteLine(h);//第10次反弹高度
Console.WriteLine(sum-h);//第10次落地距离=10次反弹距离-最后一次反弹距离

图片.png

5.我国古代数学家张丘建在《算经》一书中曾提出过著名的“百钱买百鸡”问题,该问题叙述如下:鸡翁一,值钱五;鸡母一,值钱三;鸡雏三,值钱一;百钱买百鸡,则翁、母、雏各几何?
翻译过来,意思是公鸡一个五块钱,母鸡一个三块钱,小鸡三个一块钱,现在要用一百块钱买一百只鸡,问公鸡、母鸡、小鸡各多少只?

int a = 5;
int b = 3;
double c = (double)1/3;
for (int i = 0; i < 20; i++)
{
    for (int j = 0; j < 33; j++)
    {
        int k = 100-i-j;
        if (i*a + j*b + k*c==100 && (i+j+k) == 100)
        {
            Console.WriteLine("公鸡:{0}只,母鸡:{1}只,小鸡:{2}只。", i,j,k);
        }
    }
}
 

图片.png