我很难理解这个问题。代码是非常基本的,但它的表现相当出乎意料。代码是例程的简化版本,用于从每日数据库中提取并保存到每个月的第15天的数据到单独的文件。问题出在哪儿 ?第一个cout打印输入外部if的任何一天的数量。然后有一些条件行来选择正确的日期(在这个例子中不是很重要),然后是块,内部if,应该将第15天的数据打印到新文件。现在,正如你所看到的那样,外环(注意!)仅在10日输入(这已经是错误的 - 它应该写下11到15之间的所有数字)但是它还打印出文件被写入在15!问题出在哪儿 ? OUTER IF仅在10日进入,INNER IF如何在15日执行????
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string newdata="mamma";
string risultato="-";
string PriorLine="-";
int PriorDay=0;
int lastmonth=0;
// Loops through all the months
for (int mese=1; mese <=12; mese++)
{
//Loops through all the days in the month
for(int day=1; day<=30; day++)
{
// at the month's beginning these 2 strings are set ="-"
if (mese != lastmonth)
{
risultato="-";
PriorLine="-";
}
// if we are between the 10th and the 20th and the result is still to be found
if (day>=10 && day<=20 && risultato=="-")
{
cout << day << endl; // LISTS ALL THE DAYS THIS LOOP IS ENTERED
if (day=15) // if it is exactly day 15 print that day's result
risultato=newdata;
// if that month in the data there is no day 15 and
// this is the second pass, choose the closest !
if (day>15 && PriorLine !="-")
{
if (abs(day-15)<=abs(15-PriorDay))
risultato=newdata;
else
risultato=PriorLine;
}
PriorLine=newdata;
PriorDay=day;
if (risultato != "-")
{
// writes the result ( risultato ) in a file
cout << "file written on the " << day << endl;
}
}
lastmonth=mese;
}
}
system("pause");
return 0;
}
答案 0 :(得分:7)
if (day=15)
将{15}分配给day
并返回true
。您需要if (day==15)
答案 1 :(得分:1)
当我使用g++ -Wall
简单编译代码时,我收到了警告:
error: suggest parentheses around assignment used as truth value
在这一行:
if (day=15) // if it is exactly day 15 print that day's result
我愿意成为编译器告诉你你的问题所在。我建议您在构建系统中启用所有警告。