We all have faced similar situation when our computer gets shut down with out us turning it off .. its like magic..
Typically it happens due to over heating, bad cable connection or defective battery.
1. Check all cables whether they are properly connected.
2. Check for faulty cables.
3. If computer is too hot, check the fan it might need dust clean up.
4. In case of laptop please do check your battery , it may near the end time. battery replacement will do the work.