当前位置:网站首页>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++;
}在定义输入输出时因尽量做到见名知意
边栏推荐
- [ROS] (06) ROS Communication - Topic Communication
- Linux: CentOS 7 install MySQL5.7
- 跑yolov5又出啥问题了(1)p,r,map全部为0
- C语言sizeof和strlen的区别
- Introduction and use of Haystack
- paddle window10环境下使用conda安装
- 【c】大学生在校学习c语言常见代码
- The IDEA of packaged jar package
- drf routing component Routers
- paddleocr window10 first experience
猜你喜欢

Camera Hal(Hal3)层修改Preview流

paddleocr window10初体验

The 2nd China Rust Developers Conference (RustChinaConf 2021~2022) Online Conference Officially Opens Registration

Building and getting started with the Flask framework

8580 合并链表

The IDEA of packaged jar package

动手学ocr(一)

宏定义问题记录day2
![[ROS] (02) Create & compile ROS package Package](/img/c2/5931d5cbade509c6ca34d66a274756.png)
[ROS] (02) Create & compile ROS package Package

Briefly write about the use and experience of PPOCRLabel
随机推荐
Paddle window10 environment using conda installation
The 2nd China Rust Developers Conference (RustChinaConf 2021~2022) Online Conference Officially Opens Registration
Unit 3 view layer
[ROS]ROS常用工具介绍(待续)
What are the file encryption software?Keep your files safe
The most complete ever!A collection of 47 common terms of "digital transformation", read it in seconds~
【VCU】详解S19文件(S-record)
drf routing component Routers
第七单元 ORM表关系及操作
Flask框架的搭建及入门
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第十章)
What's wrong with running yolov5 (1) p, r, map are all 0
How to solve mysql service cannot start 1069
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第十三章)
The language of initial
动手学ocr(一)
Go语言初始
[ROS] (04) Detailed explanation of package.xml
drf source code analysis and global catch exception
【ROS】编译软件包packages遇到进度缓慢或卡死,使用swap