21xrx.com
2024-09-19 09:09:40 Thursday
登录
文章检索 我的文章 写文章
C++编程练习题及解答
2023-07-05 05:51:28 深夜i     --     --
C++ 编程练习题 解答

C++是一种面向对象的编程语言,广泛用于软件和游戏开发中。C++编程语言相较于其他语言,具有高效性和可控性等优点。所以C++编程语言也成为了学霸们必须掌握的编程语言之一。学习编程最好的方法是做题,以下提供几个C++编程练习题及解答,希望对大家的学习有所帮助。

1. 编写程序将名字和分数存储到结构体数组中,并按照分数从低到高排序,然后输出结果。

解答:

#include

#include

using namespace std;

struct student

  string name;

  double score;

stu[100];

bool cmp(student a, student b)

  return a.score < b.score;

int main(){

  int n;

  cin >> n;

  for(int i = 0; i < n; i++){

    cin >> stu[i].name >> stu[i].score;

  }

  sort(stu, stu + n, cmp);

  for(int i = 0; i < n; i++){

    cout << stu[i].name << " " << stu[i].score << endl;

  }

  return 0;

}

2. 编写一个程序,将所有小写字母转换成大写字母。

解答:

#include

#include

using namespace std;

int main(){

  char str[100];

  cin >> str;

  for(int i = 0; i < strlen(str); i++){

    if(str[i] >= 'a' && str[i] <= 'z'){

      str[i] -= 'a' - 'A';

    }

  }

  cout << str << endl;

  return 0;

}

3. 编写一个程序,计算两个整数的最大公约数。

解答:

#include

using namespace std;

int gcd(int a, int b){

  if(b == 0)

    return a;

  else{

    return gcd(b, a%b);

  }

}

int main(){

  int a, b;

  cin >> a >> b;

  cout << gcd(a, b) << endl;

  return 0;

}

4. 编写一个程序,将字符串反转。

解答:

#include

#include

using namespace std;

int main(){

  char str[100];

  cin >> str;

  int len = strlen(str);

  for(int i = 0; i < len/2; i++){

    char temp = str[i];

    str[i] = str[len-1-i];

    str[len-1-i] = temp;

  }

  cout << str << endl;

  return 0;

}

以上仅是简单的C++编程练习题,每个编程题都能锻炼程序员的编程水平,提高代码编写和调试能力。当然,编程的过程中遇到困难是很正常的,需要我们要不断尝试,不断摸索,最终能够找到解决方案。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复