gpt4 book ai didi

c++ - 为什么我的代码先执行后面的cout?

转载 作者:行者123 更新时间:2023-11-30 03:57:43 25 4
gpt4 key购买 nike

下面的代码

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

bool checkPerm(unsigned long long x){
vector<unsigned long long> tester;
string strx = to_string(x);
int sizestrx = strx.size();
int counter = 1;
cout << "x is " << strx << " and its permutations are ";
while (next_permutation(strx.begin(), strx.end())){
cout << strx << " ";
unsigned long long stoipermstrx = stoi(strx);
tester.push_back(stoipermstrx);
}
cout << endl;
int sizetester = tester.size();
for (int j = 2; j <= 6; j++){
cout << "j is " << j << ' ';
for (int k = 0; k < sizetester; k++){
if (j*x == tester[k]){
cout << "counter increased because x, counter " << x << " " << counter << endl;
counter++;
if (counter == 6){
cout << "Number is " << x << endl;
return true;
}
break;
}
}
//cout << "Number " << x << " failed" << endl;
return false;
}
return true;
}

int main(){
unsigned long long x = 1;
for (double i = 0; ; i++){
cout << i << endl;
while (x < 1.67*pow(10, i)){
if (i == 5)
cout << x << endl;
if (checkPerm(x)){
cin.get();
}
x++;
}
x = pow(10, (i + 1));
}
cin.get();
}

这段代码存在以下问题:

cout << "x is " << strx << " and its permutations are ";
while (next_permutation(strx.begin(), strx.end())){
cout << strx << " ";
unsigned long long stoipermstrx = stoi(strx);
tester.push_back(stoipermstrx);
}
cout << endl;
int sizetester = tester.size();
for (int j = 2; j <= 6; j++){
cout << "j is " << j << ' ';
for (int k = 0; k < sizetester; k++){
if (j*x == tester[k]){
cout << "counter increased because x, counter " << x << " " << counter << endl;
counter++;
if (counter == 6){
cout << "Number is " << x << endl;
return true;
}
break;
}
}
//cout << "Number " << x << " failed" << endl;
return false;
}

这里的输出将是“j is j x is x and its permutations are (permutations of x)”。但是,控制台应该打印“x is x and its permutations are (permutations) j is j”。给出了以下示例输出:

j is 2 x is 1355 and its permutations are 1535 1553 3155 3515 3551 5135 5153 531
5 5351 5513 5531
j is 2 x is 1356 and its permutations are 1365 1536 1563 1635 1653 3156 3165 351
6 3561 3615 3651 5136 5163 5316 5361 5613

最佳答案

这似乎有两件(次要的)事情。第一,您没有查看 sizetester 的值在打印 j 的值之前,并且您不会在 j 的值之后打印换行符 | .这意味着您正在显示 j 的值previous loopcurrent 'x' 行的开头。如果我理解您的代码应该做什么,那么它似乎在正确地执行它——只是输出显示的方式让人感到困惑。

试试这个:

int sizetester = tester.size();
for (int j = 2; j <= 6; j++){
if (sizetester){ // <-- added test (see below)
cout << "j is " << j << '\n'; // <-- added newline
} // <--

针对 sizetester 的测试抑制 j 值的虚假打印- 你稍后测试 (k < sizetester)反正。换行符只是阻止了 j 的值从 的下一个值开始 x ,这似乎是导致输出困惑的原因。

关于c++ - 为什么我的代码先执行后面的cout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com