An average formula for the class number