C 出现不需要的换行符
每当我运行我的程序时,它直到换行后才开始打印星号,为什么? 这是我的密码:C 出现不需要的换行符,c,loops,random,newline,C,Loops,Random,Newline,每当我运行我的程序时,它直到换行后才开始打印星号,为什么? 这是我的密码: int main() { int createRow = 0, createCol; while (createRow <= 5) { while (createCol <= ((createRow * 2) - 1)) { printf("*"); createCol++;
int main()
{
int createRow = 0,
createCol;
while (createRow <= 5)
{
while (createCol <= ((createRow * 2) - 1))
{
printf("*");
createCol++;
}
createCol = 1;
createRow++;
printf("\n");
}
return 0;
}
正如你所看到的,在第一个星号之前,有一条新行。如何修复此问题?
createCol
未初始化并在分配值之前使用
执行以下更改
int createRow = 1,
createCol = 0;
while (createRow <= 5)
{
while (createCol <= ((createRow * 2)-1))
{
//Loop body
}
createCol = 0;
// Rest of the code
}
int createRow=1,
createCol=0;
而(createRow您可以通过更改
printf("\n");
到
这与以下内容相同,但更为简洁,对于知道如何使用三元运算符的程序员来说更有意义
if (createRow != 1) {
printf("\n");
}
当使用三元运算符时,条件expression1:expression2;
expression1不是必需的,但是expression2是必需的。expression1
在条件为真时执行,expression2
在条件为假时执行。在第一个astriskQ之前:您是否忘记初始化createCol?将printf(“\n”);
更改为createRow==1?:printf(“\n”)
@Jongware…三元运算符的滥用?我不认为三元运算符的这种用法是深奥的,它比if语句更简洁。只要他了解三元运算符是什么以及它是如何工作的,最好让他了解它的用法的好例子(像这样简短的一行代码)而不是链式表达式。@Jongware
createRow == 1 ?: printf("\n");
if (createRow != 1) {
printf("\n");
}