編寫演算法對輸入的一個整數,判斷它能否被3,5,7整除,並輸出一下資訊之一:
阿新 • • 發佈:2018-12-31
能同時被3,5,7整除;
能被其中兩個數(要指出哪兩個數)整除;
能被其中一個數(要指出哪一個數)整除;
不能被3,5,7任一個整除。
#include <iostream>
using namespace std;
int main()
{
int tmp;
cout<<"please enter a number:";
while(cin>>tmp)
{
int k = (tmp%3 == 0) + (tmp%5 == 0)*2 +(tmp%7 == 0)*4;
switch(k)
{
case 0: cout<<"none."<<endl;break;
case 1: cout<<"3."<<endl;break;
case 2: cout<<"5."<<endl;break;
case 3: cout<<"3 ,5"<<endl;break;
case 4: cout<<"7."<<endl;break;
case 5: cout<<"3,7"<<endl;break ;
case 6: cout<<"5,7"<<endl;break;
case 7: cout<<"3,5,7"<<endl;
}
cout<<"please enter a number:";
}
return 0;
}
演算法說明:演算法中k表示整除的情況值,為k的賦值表示式(tmp%3 == 0) + (tmp%5 == 0)*2 +(tmp%7 == 0)*4,k的範圍是0~7可以表示8中情況。既運用了算術運算的技巧,有較好地運用了“數字化”標識資訊的技巧。所以變數k的資訊含量更高,從而輸出的結果更具體。
執行結果: