问题描述
所以我在用 C++ 减去一个包含 3 的数字时遇到了麻烦 我只是做对了,也许你可以帮我分析一下
这是我的
代码:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int integer,sum = 0;
cout << "Enter an integer: ";
cin >> integer;
for (int i = 1; i <= integer; ++i) {
sum += i;
if (i == 33 || i % 10 == 3) {
i = sum - i;
}
}
cout << " The Sum is = " << sum;
getch();
return 0;
}
解决方法
这是您现有的源代码:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int integer,sum = 0;
cout << "Enter an integer: ";
cin >> integer;
for (int i = 1; i <= integer; ++i) {
sum += i;
if (i == 33 || i % 10 == 3) {
i = sum - i;
}
}
cout << " The Sum is = " << sum;
getch();
return 0;
}
-提示- 不要在全局文件范围级别使用 using std;
...
#include <iostream>
#include <conio.h>
#include <vector>
#include <fstream>
#include <string>
void loadFile(const std::string filename,std::vector<unsigned int>& contents);
unsigned int yourAlgorithm(unsigned int value);
void unitTesting(std::vector<unsigned int>& fileContents,std::vector<unsigned int>& results);
void printResults(std::vector<unsigned int>& values);
int main() {
std::vector<unsigned int> fileContents,results;
loadFile("samples.txt",fileContents);
unitTesting(fileContents,results);
printResults(results);
getch();
return 0;
}
// Functions down here:
void loadFile(const std::string filename,std::vector<unsigned int>& contents) {
// open your custom text file,either the values being separated by a space,comma delimiter,etc.
// Get each value and store it into contents.
std::fstream file(filename,std::ios_base::in);
// you can do an addition check here to see if the file does exist and if it opened correctly...
unsigned int value;
while (file >> value)
contents.push_back(value);
file.close();
}
unsigned int yourAlgorithm(unsigned int value) {
unsigned int sum = 0;
for (int i = 1; i <= value; ++i) {
sum += i;
if (i == 33 || i % 10 == 3) {
i = sum - i;
}
}
return sum;
}
void unitTesting(std::vector<unsigned int>& fileContents,std::vector<unsigned int>& results) {
unsigned int result = 0;
for (auto& v : fileContents) {
result = yourAlgorithm(v);
// I forgot to store the result in the result vector,now it's fixed.
results.push_back(result);
}
}
void printResults(std::vector<unsigned int>& results) {
for (auto& res : results) {
std::cout << res << " ";
}
std::cout << '\n';
}
如您所见,我采用了您的实现并将其移到了自己的函数中。然后设置代码以读取整数值的文本文件以填充向量。该向量将用于unit test
您的算法。然后我将您的函数或算法完全移出 main 并在 unitTesting()
函数中调用它。我也把打印功能分开,放到自己的功能里。
在这里,您可以看到这段代码结构良好,可读性强,模块化且易于调试。像这样的东西会被认为是干净的代码,很好的做法。现在请注意,这只是伪 C++ 代码。我按原样输入它,并没有通过任何编译器或调试器运行它。这是为了演示如何对代码进行单元测试,但是仅以这种方式运行算法仍然不能解决问题,您仍然必须使用调试器并逐步执行代码,逐行检查每个计算,每个比较,等等!
能够对您的算法进行单元测试是分析任何源代码的最佳方法之一,无论是您自己的代码,还是其他人的代码。我刚刚演示了一个强大而有用的工具,它应该添加到您的工具集中,它称为单元测试。
这是一个很好的 StackOverflow 答案,用于从文件中读取数据... Answer to Read Numeric Data from a Text File in C++
编辑
我忘记添加代码行以将结果存储在 unitTesting()
函数内的向量中。现已更新。