2Samuel 24 is the final chapter in this two book account of the rise and decline of David's kingship over the twelve tribes of Israel and the surrounding nations. It includes one final sin of David that results in the death of innocent people; David is a man with much blood on his hands, that of his enemies, that of his friends, that of trusting soldiers, of wayward family members, and unsuspecting citizens. But not only did David sin greatly, he also would be conscience-striken, he would cry out to God for forgiveness: "Now, LORD, I beg you, take away the guilt of your servant. I have done a very foolish thing."
It's refreshing to hear about a man who knows when he sins, is willing to admit it, and cry out for forgiveness and reconciliation. But just because David cries out for forgiveness, it doesn't mean that God is going to avert the consequences. David received pardon from God, but David had a miserable life as a husband, father, and leader. He wasn't that good of a king, but he was a great warrior; he wasn't that great of a man, but he was passionate about God. The Scriptures honest account of David's success' and failures serves us as a warning and encouragement: be warned that your sins have consequences that have to be lived/worked through; be encouraged that repentance and forgiveness are gladly given by God to those that desire it.
Whether you have sinned greatly or just a little lately, don't shirk from the consequences; let the resulting pain be both a source of character building and an incentive to resist the sin stronger next time. We can't stop sinning, but we can stop refusing to repent and request forgiveness and reconciliation. If you feel like your sins are keeping you from God, a wise step would be to confess your sins to God and take the humiliating step of requesting forgiveness, and then strength to work through the consequences within the community of believers you belong.