21xrx.com
2024-06-02 23:13:50 Sunday
登录
文章检索 我的文章 写文章
C++ 实现分糖果代码
2023-07-12 21:19:48 深夜i     --     --
C++ 分糖果 代码实现

C++可以用来实现各种各样的算法和任务,其中一个有趣的项目是实现一个分糖果的程序。在这个程序中,你可以输入一些孩子的名字和他们所想要的糖果数量,然后程序会分配糖果,确保每个孩子都能得到他们想要的数量。

为了完成这个程序,你需要用到一些基础的C++知识,例如变量、循环和条件语句。你还可以使用标准库函数来帮助你处理输入和输出。

现在让我们看看一个简单的分糖果程序的实现,代码如下:


#include <iostream>

#include <string>

#include <map>

using namespace std;

int main() {

  map<string, int> candyCounts;

  string name;

  int candyCount;

  int numChildren;

  cout << "How many children are there?" << endl;

  cin >> numChildren;

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

    cout << "Enter the name of child " << i + 1 << ":" << endl;

    cin >> name;

    cout << "Enter the number of candies " << name << " wants:" << endl;

    cin >> candyCount;

    candyCounts[name] = candyCount;

  }

  for (auto const& [name, count] : candyCounts)

    cout << name << " gets " << count << " candies." << endl;

  

  return 0;

}

这个程序首先创建了一个名为candyCounts的空映射,用于存储每个孩子想要的糖果数量。接着,它会询问你有多少个孩子,然后用循环语句逐个询问每个孩子的名字和所需的糖果数量,并将它们存储到candyCounts中。

最后,程序使用另一个循环语句遍历candyCounts中的每一项,并输出每个孩子的名字和分配给他们的糖果数量。

当你运行这个程序时,它会提示你输入孩子的名字和所需的糖果数量,然后输出分配的糖果数量。下面是一个示例运行过程的输出:


How many children are there?

4

Enter the name of child 1:

Alice

Enter the number of candies Alice wants:

2

Enter the name of child 2:

Bob

Enter the number of candies Bob wants:

3

Enter the name of child 3:

Charlie

Enter the number of candies Charlie wants:

1

Enter the name of child 4:

David

Enter the number of candies David wants:

4

Alice gets 2 candies.

Bob gets 3 candies.

Charlie gets 1 candies.

David gets 4 candies.

在这个示例中,程序询问有4个孩子,然后逐一询问每个孩子的名字和所需的糖果数量。最后输出每个孩子分配到的糖果数量。

这个简单的示例程序只是C++中的一小部分。如果你对编程感兴趣,建议你继续学习C++和其他编程语言,并尝试用它们来实现其他有趣的项目。

  
  

评论区

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