Jenna
Jenna

Reputation: 11

Converting seconds (clocks) to decimal format

I'm making a stopwatch, and I need to output the seconds out like so: "9.743 seconds".

I have the start time, the end time, and the difference measured out in clocks, and was planning on achieving the decimal by dividing the difference by 1000. However, no matter what I try, it will always output as a whole number. It's probably something small I'm overlooking, but I haven't a clue what. Here's my code:

#include "Stopwatch.h"
#include <iostream>
#include <iomanip>
using namespace std;
Stopwatch::Stopwatch(){
    clock_t startTime = 0;
    clock_t endTime = 0;
    clock_t elapsedTime = 0;
    long miliseconds = 0;
} 

void Stopwatch::Start(){
        startTime = clock();
}
void Stopwatch::Stop(){
        endTime = clock();
}
void Stopwatch::DisplayTimerInfo(){
    long formattedSeconds;
    setprecision(4);

    seconds = (endTime - startTime) / CLOCKS_PER_SEC;
    miliseconds = (endTime - startTime) / (CLOCKS_PER_SEC / 1000);

    formattedSeconds = miliseconds / 1000;
    cout << formattedSeconds << endl;

    system("pause");    
}

Like I said, the output is integer. Say it timed 5892 clocks: the output would be "5".

Upvotes: 1

Views: 1730

Answers (2)

Bhavesh Kumar
Bhavesh Kumar

Reputation: 116

formattedSeconds =(double) miliseconds / 1000;

it will give you real number output

Upvotes: 1

selbie
selbie

Reputation: 104484

Division between integers is still an integer. Cast one of your division parameters to a real type (double or float) and assign to another variable that is a real type.

double elapsedSeconds = (endTime - startTime) / (double)(CLOCKS_PER_SEC);
cout << elapsedSeconds << endl;

Upvotes: 2

Related Questions