C++课本第三章例题
3-2 输入一个8位二进制数,将其转换为十进制数输出。
1 #include <iostream> 2 using namespace std; 3 double power(double x,int n); //函数的声明,double类型防止超出整型 4 int main() 5 { 6 int number=0; 7 for(int i=7;i>=0;i--) //进行八次循环,输入一个8位二进制数 8 { 9 char ch; // int 输入的不是字符串,或字符。而是整数, 所以用char型 10 cin>>ch; 11 if(ch=='1') //如果是1的话就进行计算,否则不用计算 12 { 13 number+=static_cast<int>(power(2,i)); 14 } 15 } 16 cout<<number<<endl; 17 } 18 double power(double x,int n) //函数的定义 19 { 20 double a=1.0; 21 while(n--) 22 { 23 a*=x; 24 } 25 return a; 26 }
输出Π的值
#include <iostream> #include <cmath> using namespace std; double fab(double x) { double sqr=x*x; double e=x; double r=0; int i=1; while(e/i>1e-15) { double f=e/i; r=(i%4==1)?r+f:r-f; e=e*sqr; i+=2; } return r; } int main() { double pai; pai=16.0*fab(1.0/5)-4.0*fab(1.0/239); cout<<pai; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?