一、判断水仙花数
二、代码实现
diffodils.cppper
#include<iostream>
#include<thread>
#include<stdlib.h>
#include"perfect.h"
#include"threadguard.h"
int main(int argc,char*argv[]){
int n=atoi(argv[1]);
Perfect pf(n);
std::thread t(pf);
ThreadGuard tg(std::move(t));
return 0;
}
perfect.h
#include<iostream>
class Perfect{
public:
Perfect(int n):n(n){}
void operator()();
private:
int factorSum(const int n);
int n;
};
perfect.cpp
#include<iostream>
#include"perfect.h"
void Perfect::operator()(){
if(factorSum(n) == n){
std::cout<<"yes\n";
}else{
std::cout<<"no\n";
}
}
int Perfect:: factorSum(const int n){
int a,b,c;
a=n%10;
b=n/10%10;
c=n/100;
return a*a*a+b*b*b+c*c*c;
}
threadguard.h
#include<iostream>
#include<thread>
class ThreadGuard{
public:
ThreadGuard(std::thread t):t_(std::move(t)){}
~ThreadGuard();
ThreadGuard(ThreadGuard&)=delete;
ThreadGuard& operator =(ThreadGuard&)=delete;
private:
std::thread t_;
};
threadguard.cpp
#include"threadguard.h"
ThreadGuard::~ThreadGuard(){
if(t_.joinable()){
t_.join();
}
}
shm.mk
GCC=g++
CFLAG=-c
OFLAG=-o
SLIB=-pthread
SEXE=diffodils
SOBJ=diffodils.o perfect.o threadguard.o
${SEXE}:${SOBJ}
${GCC} ${OFLAG} $@ $^ ${SLIB}
%.o:%.cpp
${GCC} ${CFLAG} $^
clean:
rm *.o
~