c1803 黄文博 第三次作业

c语言第三次作业 10.15

1.IsPrime():判断一个数字是否为素数;返回值是1时 说明是素数,返回值是0,则非素数;
举例:
bool ISprime(int n)
{
int i,isqrt=(int)sqrt(n);//sqrt函数用来计算平方根
if(n<=2)
return (n2);
else if(n%2
0) //首先,排除偶数,就只剩奇数了
return false;
else
for(i=3;i<=isqrt;i+=2)//再排除奇数里面的能开方的数就只剩素数了,比如49
{
if(n%i==0){
return false;
}
}
return true;
}
/*
#include
是素数返回true
不是返回false
*/
2.aseet:断言(精准判断哪一行代码有错误),它有对应的头文件<assert.h>;
assert针对的是Debug版本(程序员版本),那么,对应的还有Release版本(用户版本)
在这里插入图片描述

在这里插入图片描述
举例:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;

   fp = fopen( "test.txt", "w" );//以可写的方式打开一个文件,如果不存在就创建一个同名文件
   assert( fp );                           //所以这里不会出错
   fclose( fp );

   fp = fopen( "noexitfile.txt", "r" );//以只读的方式打开一个文件,如果不存在就打开文件失败
   assert( fp );                           //所以这里出错
   fclose( fp );                           //程序永远都执行不到这里来
   return 0;

}
3.switch case 语句:作为一种选择语句,它比if语句优秀,能提供多个分支。
说明:
3.1 switch后面 的括弧内的表达式的值只能是整型或字符型。常量表达式的类型必须与switch语句中的表达式的类型一致。
3.2可以省略default语句,这时,switch语句未找到与switch表达式中的值相匹配的case常量,switch语句就跳转到他的下一条语句,即跳出switch语句。
3.3 case后跟的是冒号:
3.4每个case中的执行语句一定要加break
练习:char 类型在switch 中的使用

public static void main(String[] args) {
int x = 1, y = 2;
char ch = '’;
switch (ch) {
case ‘+’:
System.out.println("x
y=" + (x + y));
break;
case ‘-’:
System.out.println(“x-y=”+(x-y));
break;
case '’:
System.out.println("x
y="+(xy));
break;
case ‘/’:
System.out.println(“x/y=”+(x/y));
break;
default:
System.out.println(“error”);
}
}
编译输出:x
y=2;

猜你喜欢

转载自blog.csdn.net/qq_43395214/article/details/83059623
今日推荐