我用c ++编写了一个执行某些任务的程序。用户选择将完成哪些操作。首先,程序将完成用户选择的所有操作,但是它会等待用户指定的时间(以秒为单位)再次执行某项任务;任务可以有不同的等待时间。
在我的电脑中,它工作正常,但是我把可执行文件交给了某人,他告诉我它第一次完成了他选择的任务(他只是选择了任务3),但是等待时间结束了,它什么都不做。我不知道问题的根源,它与我使用的相同.exe文件在我的计算机上工作正常,行为应该是相同的,但由于某种原因它不是。
我使用了msvc 2012.是的,用户拥有Visual C ++ Redistributable。
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
int GetLowestWaitingTime(int* a)
int main()
{
int WaitingTime[3];
int TimeForTask[3];
bool task[3];
int i;
cout<<"1=yes 0=no. Press enter after you have typed the chosen number" <<endl;
for(i = 0; i < 3;i++){
cout<<"Do you want task " <<i+1 <<" to be performed? ";
cin >> task[i];
if(task[i])
{
cout<<"Enter the waiting time for task " <<i+1 <<" in seconds: ";
cin >> TimeForTask[i];
}else{
TimeForTask[i] = -1;
}
WaitingTime[i] = 0;
}
while(1)
{
for(i = 0; i < 3; i++){
if(task[i] && WaitingTime[i] == 0)
{
//Do task i+1
WaitingTime[i] = TimeForTask[i];
}
}
SleepTime = GetLowestWaitingTime(WaitingTime);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) 2); //turn off monitor
Sleep(SleepTime*1000);
for(i = 0; i < 3; i++)
{
if(WaitingTime[i] != -1){
WaitingTime[i] -= SleepTime;
}
}
}
return 0;
}
int GetLowestWaitingTime(int* a)
{
int l = -2;
if(a[0] != -1 && ((a[0] < a[1]) || (a[1] == -1))){
l = a[0];
}else if(a[1] != -1){
l = a[1];
}
if(l == -2){l = a[2];}else if(l > a[2] && a[2] != -1){l = a[2];}
return l;
}
答案 0 :(得分:0)
你为每个索引设置WaitingTime为0,但你的标记是-1,所以你总是得到睡眠时间0。
请尝试以下for while循环:
while(1)
{
for(i = 0; i < 3; i++){
if(task[i] && WaitingTime[i] == 0)
{
//Do task i+1
WaitingTime[i] = TimeForTask[i];
}
else
{
WaitingTime[i] = -1;
}
}
SleepTime = GetLowestWaitingTime(WaitingTime);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) 2); //turn off monitor
Sleep(SleepTime*1000);
for(i = 0; i < 3; i++)
{
if(WaitingTime[i] != -1){
WaitingTime[i] -= SleepTime;
}
}
}