变量似乎在自行改变值
Variables seem to be changing value on their own
好的,所以我的项目是一个分析.txt文件的程序,该文件包含一堆不同长度的DNA链。我把它全部用于3个函数,但我的老师希望我们使用oo编程。所以我把我的代码放在一个类中,并把它分解成不同的函数。然而,现在我的变量似乎随机改变了它们的值,我不知道为什么。
我用我的"sum"变量运行了一系列测试(但它不是唯一一个这样做的变量),它计算出函数中的正确值,但如果我在main中重新计算"sum"的值,这个值就会变成一个荒谬的数字。
这是代码:问题变量在哪里以及如何使用它并不是我的整个程序。如果这还不足以显示问题,我可以添加更多,我只是不想让它变得混乱。
DNA处理.cpp
void DNAProcessing::CalcSumAndMean()
{
int lineLength = 0;
int lineCounter = 0;
int wholeFileStringLen = 0;
double sum = 0;
double mean = 0;
string wholeFileString = "";
string line;
bool filefail = false;
ifstream DNAFile;
DNAFile.open(nameoffile.c_str());
if(DNAFile.fail())
{
filefail = true;
return;
}
else
{
cout << "nYour data was processedn" << endl;
}
while(DNAFile >> line)
{
//cout << line << endl;
lineCounter += 1;
lineLength = line.length();
sum += lineLength;
wholeFileString += line;
}
cout << "sum: " << sum << endl; // with my test .txt file this outputs 736
mean = (sum / lineCounter);
wholeFileStringLen = wholeFileString.length();
cout << "sum: " << sum << endl; // with my test .txt file this outputs 736
}
main.cpp
int main()
{
srand(time(0));
bool noexit = true;
string yesorno;
string filename;
while(noexit == true)
{
cout << "Would you like to process a list of DNA strings? (y/n)" << endl;
cin >> yesorno;
if((yesorno == "y") || (yesorno == "Y" ))
{
cout << "please input the name of the file you wish to process." << endl;
cin >> filename;
DNAProcessing DNAStrandFile(filename);
DNAStrandFile.CalcSumAndMean();
cout << "sum: " << DNAStrandFile.sum << endl; //for some reason sum turns into 3.18337e-314 and i have no clue why
if (DNAStrandFile.filefail == false)
{
cout << "sum: " << DNAStrandFile.sum << endl; // same here
DNAStrandFile.CalcNucleobaseRelProb();
DNAStrandFile.CalcBigramRelProb();
DNAStrandFile.CalcVarianceAndStndDev();
DNAStrandFile.CalcNormRand();
DNAStrandFile.PrintData();
DNAStrandFile.PrintNewList();
}
else
{
cerr << "No file found" << endl;
}
}
else if((yesorno == "n") || (yesorno == "N"))
{
noexit = false;
}
else{}
}
}
将我的test.txt文件传递到此程序时输出
sum: 736
sum: 736
sum: 3.18337e-314
sum: 3.18337e-314
由于sum被声明为double,它的值0可能不会精确地存储为零,因此出于所有实际目的,3.18337e-314的值可以被视为零。您可以定义一个阈值
double epsilon = 0.00001 ; // depending on precision
并且如果sum<ε,sum=0.0(但不需要)在您的示例中,您也使用sum作为局部变量,或者不声明局部变量,只使用成员变量,或者将局部变量声明为不同的名称,以避免混淆
局部变量的值在函数的范围内是有效的,这就是为什么您在方法中得到了正确的答案。但是没有返回任何值,因此在main中打印垃圾值。
尝试通过引用发送方法中的变量,然后它们的确切值也将在main中可用。试试看。
相关文章:
- 变量没有改变?通过向量的函数调用
- 在向量内更改变量的值不会改变其在向量外的值
- C++11:具有互斥锁的线程看到原子变量的值发生变化,尽管这是唯一可以改变它的代码
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 标准在哪里定义了可变变量可以改变
- C++11:可变的 lambda 似乎没有改变变量?
- printf() 似乎改变了一个变量
- 为什么我的变量在单独的线程中修改时没有改变?C++/boost
- 为什么 Player.x 和 Player.y 变量没有改变?
- C - 如何将各处的静态函数称为改变其私有变量
- 即使"friend class rect"在平方类中被评论,为什么它要改变矩形类的私有变量?
- 为什么调用 CUDA 内核函数时这个类成员变量没有改变
- 全局变量的顺序会改变C /OpenGL的性能
- 为什么一个函数的末尾有常量这个词,即使它确实改变了一个变量
- 如何在C++中改变超类和子类的变量
- setRoomName不会改变变量roomName
- 不能改变变量的值
- 是否有一种方法可以改变变量在内存中的存储方式(位大小)
- Std::cout改变变量的值
- 使用引用改变变量的地址