#include <iostream>
int main(){
for (int i = 1; i <=5; i++){
if (i == 3)
char i[3] = "abc";
std::cout << i << "\n";
}
}
输出:
1
2
3
4
5
因此,问题在于
char i[3]
仅在if范围内,并且如果我尝试在if语句中使用cout
,它将按预期方式显示"abc"
,但在if语句之外不起作用,我可以称之为好像不粘因此,如何声明它以便它在if语句之外起作用,并且我不想在if语句内添加cout
,也不想在for循环中更改cout
,因为在我的实际程序我正在打印一张桌子。更新:这是我的实际代码:
#include <iostream>
#include <iomanip>
#include <cmath>
#define pi 3.14159265359
double d2r(int deg) {
double rad = (pi * deg) / 180;
return rad;
}
int main() {
int sw = 2;
cout << "Deg" << "\t"
<< "Sin" << "\t"
<< "Cos" << "\t"
<< "Tan" << "\t"
<< "\n";
for (int deg = 2; deg <= 90; deg += 2) {
double A = sin(d2r(deg));
double B = cos(d2r(deg));
double C = tan(d2r(deg));
if (abs(B) < 0.00009)
B = 0;
if (abs(C) > 100)
char C[4] = "Inf";
cout << setprecision(3) << fixed
<< deg << setw(sw) << "\t"
<< A << setw(sw) << "\t"
<< B << setw(sw) << "\t"
<< C << setw(0) << "\n";
}
}
最佳答案
您无法像尝试那样更改C
的类型。对于不同的数据类型,您需要单独的cout <<
语句,例如:
cout << setprecision(3) << fixed
<< deg << setw(sw) << "\t"
<< A << setw(sw) << "\t"
<< B << setw(sw) << "\t";
if (abs(C) > 100)
cout << "Inf";
else
cout << C;
/* alternatively:
(abs(C) > 100) ? (cout << "Inf") : (cout << C);
*/
cout << setw(0) << "\n";
或者,根据所需条件设置
std::string
格式,然后输出该字符串,例如:std::ostringstream oss;
if (abs(C) > 100)
oss << "Inf";
else
oss << setprecision(3) << fixed << C;
/* alternatively:
(abs(C) > 100) ? (oss << "Inf") : (oss << setprecision(3) << fixed << C);
*/
cout << setprecision(3) << fixed
<< deg << setw(sw) << "\t"
<< A << setw(sw) << "\t"
<< B << setw(sw) << "\t"
<< oss.str() << setw(0) << "\n";
关于c++ - 在if范围内更改变量的类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47781369/