幾道簡單的程式設計練習

2021-06-17 15:09:14 字數 1988 閱讀 3082

分段函式求值講解

題:從鍵盤輸入x

的值(要求為實型),根據以下公式計算並輸出x和

y的值要求採用兩種解法完成,解法1

用if else 

語句,解法

2主體用

switch 語句

注意:分段的關鍵點處,x

的值均是偶數;

x<0 

是非法的輸入,程式應該作出處理

sol 1:

#include

#include

using namespace std;

int main ()

float x,y;

cout<<"please enter x:";

cin>>x;

if (x<0)

cout<<"wrong"if (x<2)

y=x;

else if (x<6)

y=x*x+1;

else if (x<10)

y=sqrt (x+1);

else y=1/(x+1);   x為

float型,1

為整型,

x+1為

double

型,則y

也為double型

cout<<"x="sol 2:

switch()括號中的量不能為浮點型,因為浮點型比較存在誤差,

case

後面只能跟常量

注意到分段的關鍵點處,x

的值均是偶數,可以通過取整,強制型別轉換 

int(x)

/2#include

#include

using namespace std;

int main ()

float x,y;

int c;

cout<<"please enter x:";

cin>>x;

if (x<0)

cout<<"wrong"c=int(x)/2;

switch (c)

case 0: y=x; break;

case 1:

case 2: y=x*x+1;break;

case 3:

case 4:y=sqrt (x+1);break;

default: y=1/(x+1); 

cout<<"x="個人所得稅計算器

題:編寫選擇結構程式,輸入個人月收入總額,計算出他本月應繳稅款和稅後收入

1 用if語句的巢狀  2 用

switch 語句

同上題當用switch

語句時,可以先用

if else 

定義switch

()括號中的變數的常量值

例:int istep;

if (

dvalue<=1500)

istep = 1;

switch (step)

case 1: 

利息計算器:

題:輸入存款金額並選擇存款種類,計算出利息(不計利息稅)和本息合計,要求使用switch

語句,根據選擇的存款種類。確定利率和存期後計算。

sol:

#include

#include

using namespace std;

int main ()

int type,days;

double money,period,rate,interest;

cout<<"welcome to use the interest calculator"cin>>money;

cout<<"*****please choose the type*****"cin>>type;

if (type>=1&&type<=7)

switch (type)

interest=money*period*rate;

cout<<"the interest is:"

複習 c語言幾道簡單程式設計題

最近在複習c語言的一些知識點,以下是整理的幾道比較重要的程式設計題 1.列印100 200之間的素數 為了統計素數的個數,可設定乙個計數器count 方法1 includeint main if j i printf ncount d n count system pause return 0 方法...

幾道題 Tarjan練習

tarjan的教程網上都有 cogs8 備用交換機 7 1 2 2 3 2 4 3 4 4 5 4 6 4 7 5 6 6 7輸出檔名 gd.out 2 2 4求割點 include include include include include using namespace std struct...

幾道練習題

使用map函式 將字串列表 轉化 lxx.ab 形式 方法一 迭代器形式解題 name lxx lj dsvsf def func item name中的每一項都傳過來 循壞item return item sb name1 map func,name map 函式名,可迭代的 name1是乙個迭代...