当前位置:网站首页>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++;
}
在定义输入输出时因尽量做到见名知意
边栏推荐
- Unit 5 Hold Status
- Flask请求应用上下文源码分析
- 【Camera2】由Camera2 特性想到的有关MED(多场景设备互动)的场景Idea
- [ROS] The difference between roscd and cd
- jwt (json web token)
- Haystack的介绍和使用
- 网络剪枝(1)
- Building and getting started with the Flask framework
- verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第十三章)
- Steps to connect the virtual machine with xshell_establish a network connection between the host and the vm virtual machine
猜你喜欢
随机推荐
How to solve mysql service cannot start 1069
宏定义问题记录day2
[ROS] Introduction to common tools in ROS (to be continued)
yolov5 improvement (1) Add attention focus mechanism
Unit 8 Middleware
chapter7
深度学习框架pytorch快速开发与实战chapter3
【c】小游戏---扫雷雏形
Steps to connect the virtual machine with xshell_establish a network connection between the host and the vm virtual machine
c语言用scanf出错不安全的解决办法
Deep learning framework pytorch rapid development and actual combat chapter3
【ROS】工控机的软件包不编译
Web Design (Beginners) [easy to understand]
A little thought about password encryption
window10 lower semi-automatic labeling
Unit 14 Viewsets and Routing
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第十章)
[ROS](04)package.xml详解
Flask contexts, blueprints and Flask-RESTful
drf source code analysis and global catch exception