21xrx.com
2025-03-29 10:23:38 Saturday
文章检索 我的文章 写文章
C++有趣简单代码大全
2023-07-01 12:25:34 深夜i     24     0
C++ 有趣 简单 代码 大全

C++是一种高效的编程语言,许多程序员都热爱它。无论您是初学者还是有经验的程序员,都可以在C++中编写有趣而简单的代码。

以下是C++简单而有趣代码的一些示例:

1. 打印乘法表

使用简单for循环可以编写出打印乘法表的代码。

#include<iostream>
using namespace std;
int main()
{
  int n,i;
  cout<<"Enter the Number for Multiplication Table: ";
  cin>>n;
  for(i=1;i<=10;i++)
  {
   cout<<n<<" x "<<i<<" = "<<n*i<<endl;
  }
  return 0;
}

2. 猜数字游戏

编写一个简单的猜数字游戏,这是一个有趣的代码。

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
  int n,guess,attempt=0;
  srand(time(0));
  n=rand()%100 + 1; //生成1-100的随机数
  do
  {
   attempt++;
   cout<<"Enter your guess between 1 and 100: ";
   cin>>guess;
   if(guess>n)
     cout<<"Guess is Too High! Try again!"<<endl;
   else if(guess<n)
     cout<<"Guess is Too Low! Try again!"<<endl;
   else
     cout<<"Congratulations! You Guessed the Number in "<<attempt<<" attempts!"<<endl;
  }while(guess!=n);
  return 0;
}

3. 判断素数

编写一个简单的程序来判断一个数是否为素数。

#include<iostream>
using namespace std;
int main()
{
  int n,i;
  bool isPrime=true;
  cout<<"Enter a Positive Integer: ";
  cin>>n;
  for(i=2;i<=n/2;i++)
  {
   if(n%i==0)
   
     isPrime=false;
     break;
   
  }
  if(isPrime)
   cout<<n<<" is a Prime Number"<<endl;
  else
   cout<<n<<" is Not a Prime Number"<<endl;
  return 0;
}

4. 递归

使用递归函数打印斐波那契数列。

#include<iostream>
using namespace std;
int fib(int n)
{
  if(n<=1)
   return n;
  return (fib(n-1)+fib(n-2));
}
int main()
{
  int n,i;
  cout<<"Enter the Number of terms for Fibonacci Series: ";
  cin>>n;
  cout<<"Fibonacci Series for "<<n<<" terms: "<<endl;
  for(i=0;i<n;i++)
   cout<<fib(i)<<" ";
  cout<<endl;
  return 0;
}

这些都是C++简单而有趣的代码示例。使用这些示例来解决不同的问题,并且学习更多关于C++编程的知识。

  
  

评论区