牛客网初阶练习(7)

x33g5p2x  于2022-02-09 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(190)

1.简单计算器

2.带空格直角三角形图案

方法1:

方法2:

  1. 有序序列插入一个数​

1.简单计算器

#include<stdio.h>
int main()
{
	double n1 = 0.0;
	double n2 = 0.0;
	char ch = ' ';

	while (scanf("%lf%c%lf", &n1, &ch, &n2) != EOF)
	{
		switch (ch)
		{
		case '*':
			printf("%.4lf%c%.4lf=%.4lf\n", n1, ch, n2, n1 * n2);
			break;

		case '+':
			printf("%.4lf%c%.4lf=%.4lf\n", n1, ch, n2, n1 + n2);
			break;
		case '/':
			if (n2 == 0)
			{
				printf("Wrong!Division by zero!\n");
				break;
			}
			else
				printf("%.4lf%c%.4lf=%.4lf\n", n1, ch, n2, n1 / n2);
			break;
		case '-':
			printf("%.4lf%c%.4lf=%.4lf\n", n1, ch, n2, n1 - n2);
			break;
		default:
			printf("Invalid operation!\n");
		}
	}

	return 0;
}

2.带空格直角三角形图案

方法1:

先打印空格,再打印*。

#include<stdio.h>
int main()
{
    int n = 0;
    while(scanf(" %d",&n)!=EOF)
    {
        int i = 0;
        for(i = 0;i<n;i++)
        {
            int j = 0;
            for(j = 0;j<n-i-1;j++)
            {
                printf("  ");
            }
            for(j = 0;j<=i;j++)
            {
                printf("* ");
            }
            printf("\n");
        }
    }
    return 0;
}

方法2:

(找规律)

#include<stdio.h>
int main()
{
	int n = 0;
	while (scanf("%d", &n) != EOF)
	{
		int i = 0;
		for ( i = 0; i < n; i++)
		{
			int j = 0;
			for (j = 0; j < n; j++)
			{
				if (i + j < n-1)
				{
					printf("  ");
				}
				else
				{
					printf("* ");
				}
			}
            printf("\n");
		}
	}
	return 0;
}

3. 有序序列插入一个数

#include<stdio.h>
#include<malloc.h>
int main()
{
    int N = 0;
    int X = 0;
    scanf("%d",&N);
    int *arr = (int*)malloc(sizeof(int)*(N+1));
    arr[N] = 0;
    for(int i = 0;i<N;i++)
    {
        scanf("%d",&arr[i]);
    }
    scanf("%d",&X);
    int i =0;
    for(i = N-1;i>=0;i--)
    {
        if(arr[i]>X)
        {
            arr[i+1] = arr[i];
        }
        else
        {
            arr[i+1] = X;
            break;
        }
    }
    if(i<0)
    {
        arr[0] = X;
    }
    for(int i = 0;i<N+1;i++)
        {
            printf("%d ",arr[i]);
        }
    return 0;
}

相关文章