当前位置:网站首页>C语言初级—常见问题(100~200素数,计算1+11+111+...,从键盘获取一个数并输出有几个位)
C语言初级—常见问题(100~200素数,计算1+11+111+...,从键盘获取一个数并输出有几个位)
2022-08-02 14:03:00 【iccoke】
输出100~200之间的素数
具体代码
#include<stdio.h>
int main()
{
int num = 100;
int i;
while (num <= 200)
{
for (i = 2; i < num; i++)
{
if (num % i == 0)
break;
}
if (i == num)
{
printf("100~200之间的素数有%d\n", num);
}
num++;
}
return 0;
}首先要求100~200之间获取素数,在判断前给出约束条件
函数体利用素数特性,即除去一和它本身不能有别的除数
计算1+11+111+...
在给出具体代码之前,观察加数形式,11,111
得出计算加数的关键代码
即 b = b + (int)a * pow(10, i)
由于pow函数计算后默认为double类型,因此这里用(int)进行强制转换
其次在用pow等其他数学函数时,头文件因加上#include<math.h>
具体代码如下
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
int getsum(int n) {
int a=1;
int sn=0;
int b = 0;
for (int i = 0; i < n; i++)
{
b = b + (int)a * pow(10, i);
sn = sn + b;
}
return sn;
}
int main() {
int n;
scanf("%d", &n);
int result = getsum(n);
printf("%d\n", result);
return 0;
}从键盘获取一个整形并输出有几位
基本思想:数字每能被十除一次并得到大于一的数,则可以加位
具体代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
int main()
{
double num;
int a = 1;
scanf("%lf", &num);
while (10<=num )
{
num = num / 10;
a += 1;
}
printf("这是个%d位数字\n", a);
return 0;
}优化
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
int main(){
int num;
scanf("%d", &num);
int count = 0;
while (num != 0);
{
num /= 10;
count++;
}在定义输入输出时因尽量做到见名知意
边栏推荐
- drf路由组件Routers
- [ROS]ROS常用工具介绍(待续)
- Flask contexts, blueprints and Flask-RESTful
- What's wrong with running yolov5 (1) p, r, map are all 0
- verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第九章)
- Building and getting started with the Flask framework
- A little thought about password encryption
- Unit 13 Mixing in View Base Classes
- 网络剪枝(1)
- drf视图组件
猜你喜欢

宏定义问题记录day2

STM32 (F407) - stack

函数递归和动态内存初识
![[ROS] The software package of the industrial computer does not compile](/img/a8/a1347568170821e8f186091b93e52a.png)
[ROS] The software package of the industrial computer does not compile

8580 Merge linked list
![[ROS] (05) ROS Communication - Node, Nodes & Master](/img/f5/c541259b69a0db3dc15a61e87f0415.png)
[ROS] (05) ROS Communication - Node, Nodes & Master

8581 线性链表逆置

Unit 13 Mixing in View Base Classes

MobileNet ShuffleNet & yolov5替换backbone

Building and getting started with the Flask framework
随机推荐
jwt(json web token)
Unit 3 view layer
jwt (json web token)
Verilog学习 系列
STM32(F407)—— 堆栈
(ROS) (03) CMakeLists. TXT, rounding
drf source code analysis and global catch exception
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第十二章)
Flask项目的完整创建 七牛云与容联云
第三单元 视图层
宏定义问题记录day2
Flask request application context source code analysis
What are the file encryption software?Keep your files safe
[ROS] (01) Create ROS workspace
Visual Studio配置OpenCV之后,提示:#include<opencv2/opencv.hpp>无法打开源文件
Linux: CentOS 7 install MySQL5.7
How does Apache, the world's largest open source foundation, work?
Flask框架深入二
Unit 15 Paging, Filtering
【c】大学生在校学习c语言常见代码