C语言/C++常见习题问答集锦(十)
程序之美
1、求圆的体积
#include <stdio.h>
int main ()
{
float h,r,l,s,sq,vq,vz;
float pi=3.141526;
printf("请输入圆半径r:");
scanf("%f",&r); //要求输入圆半径r和圆柱高h
sq=4*pi*r*r; //计算圆球表面积sq
vq=3.0/4.0*pi*r*r*r; //计算圆球体积vq
printf("圆球表面积为: sq=%6.2f\n",sq);
printf("圆球体积为: v=%6.2f\n",vq);
return 0;
}
2、C语言 输入n=5,打印出下图的菱形
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int i = 0;
int j = 0;
int line = 0;
printf("输入n=");
scanf("%d",&line);//要打印的正三角的行数
line = line / 2 + 1;
//正三角
for (i = 1; i <= line; i++) //控制行数
{
//先打印空格
for (j = 1; j <= (line - i); j++) //正三角中需要打印空格的行数为正三角的行数-1(最后一行不用打空格)
{
printf(" ");
}
//再打印*
for (j = 1; j <= 2 * i - 1; j++)
{
printf("*");
}
printf("\n");
}
//倒三角
for (i = 1; i < line; i++) //控制行数
{
//先打印空格
for (j = 1; j <= i; j++)
{
printf(" ");
}
for (j = 1; j <= 2 * (line - i)-1; j++)
//再打印*
{
printf("*");
}
printf("\n");
}
system("pause");
return 0;
}
3、编程实现“天天向上的力量”(假设初值为一,每天学习,进步1%,每天不学习,退步1%,一年以后对比学习结果)。程序和结果拍照上传,对比结果,发表看法。
#include<stdio.h>
#include<math.h>
int main(){
double N = 365.0;
double v1 = 1.0 + 0.01;
double v2 = 1.0 - 0.01;
double s1 = pow(v1, N);
double s2 = pow(v2, N);
printf("每天进步百分之一,一年后为:%4.3f\n", s1);
printf("每天退步百分之一,一年后为:%4.3f\n", s2);
return 0;
}
4、用二维数组实现输出杨辉三角前六行
include<stdio.h>
void main()
{
int sz[6][6],i,j;
for(i=0;i<=5;i )
{
sz[i][0]=1;
sz[i][i]=1;
}
for(i=2;i<=5;i )
for(j=1;j<=i-1;j )
sz[i][j]=sz[i-1][j-1] sz[i-1][j];
for(i=0;i<=5;i )
for(j=0;j<=i;j )
{
printf("%-4d",sz[i][j]);
if(j==i) printf(" ");
}
getchar();
}
5、编写一个学生和教师数据输入和显示程序。其中,学生数据有编号、姓名、班级和成绩,教师数据有编号、姓名、职称和部门。要求将编号、姓名输入和显示设计成一个类 Person;然后设计类 Person 的派生类:学生类 Student 和教师类 Teacher;编写一个主函数,通过定义 student、teacher 的对象,完成相应功能。
#include<iostream>
#include<string>
using namespace std;
class Person{
public:
Person(stringname1,int number1)
{
name=name1;
number=number1;
}
void print()
{
cout<<"姓名:"<<name<<endl;
cout<<"编号:"<<number<<endl;
}
protected:
string name;
int number;
};
class Student:public Person{
public:
Student(stringname1,int number1,int class_number1,int score1):
Person(name1,number1)
{
class_number=class_number1;
score=score1;
}
void print(){
Person::print();
cout<<"班号:"<<class_number<<"成绩:"<<score<<endl;
}
protected:
intclass_number;
int score;
};
class Teacher:public Person{
public:
Teacher(stringname1,int number1,string professional title1,string dept1):
Person(name1,number1)
{
professionaltitlel=professioal title1;
dept=dept1;
}
void print()
{
Person::print();
cout<<"职称:"<<professionaltitle<<"部门:"<<dept<<endl;
}
protected:
string professional title;
string dept;
};
int main()
{
Student my_Student("梁焕瑜",13,1141,95);
cout<<"学生:"<<endl;
my_Student.print();
Teacher my_Teacher("易学明",01,"教授","信息部");
cout<<"教师:"<<endl;
my_Teacher.print();
return 0;
}