- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我收到了一个赋值问题,到目前为止我已经设法解决了所有问题,除了在几个(输入确定的)字符之间分割余数值之外。任何帮助将不胜感激。作为引用,我的作业问题是:
“如果你看报纸,你会发现文字是对齐的,适合各栏。编写一个程序,读取报纸中栏的宽度,然后读取一行文本。对齐文本行适合该宽度的列。当您的程序运行时,屏幕应如下所示:
Enter the width of the column: 40Enter a line of text: Good morning how are you?12345678901234567890123456789012345678901234567890...Good morning how are you?
The justification is done by counting the number of gaps in the text. In the above example, there are 4 gaps. Then each gap must have spaces added to it. The number of extra spaces must be shared out as evenly as possible. In the above example, the first three gaps have 5 spaces each and the last gap has 4 spaces.
Notes:
"
And my code so far is:
int main() {
//input column width
printf("Enter the width of the column: ");
int column;
scanf("%d", &column);
//input text line
printf("Enter a line of text: ");
char string[80];
getchar();
gets(string);
//print 1234567890 column header
int y = 1,x = 0;
while(x < column){
if(y > 9){
y = 0;
}
printf("%d", y);
y++;
x++;
}
printf("\n");
//count spaces
int i = 0;
int space_count = 0;
while(string[i] != '\0'){
if(string[i] == 0x20){
space_count++;
}
//printf("%c", string[i]);
i++;
}
//work out variables
int string_length = i;
int remainder_space = (column - string_length);
int space_power = (remainder_space / space_count);
//int oddremainder = (space_count % remainder_space) ;
//space_power = (space_power + oddremainder);
//if
//remainder %
//insert column width check
if(string_length > column)
{
printf("Text is too long. Shouldn't be more than %dcharacters\n",
column);
return 1;
}
//output
i = 0;
while(string[i] != '\0'){
if(string[i] == 0x20){
for(x = 0; x < space_power; x++){
printf("%c", 0x20);
}
}
printf("%c", string[i]);
i++;
}
如果这不是提问的正确方式,我很抱歉,我的大脑已经崩溃了,我无法理解这个问题。任何正确方向的指示或讨论将不胜感激。
最佳答案
让我们看一下示例。它有 19 个空格需要填补 4 个空白。如果您的代码像这样运行,则 space_power
的值将为 4 (int(19/4)),最后会留下 3 个空格。您需要跟踪 19 % 4,即。 3 个额外空格。
因此,保留一个计数,最初等于 3。然后,当该计数大于 0 时,打印一个额外的空格以及所有 space_power
数量的空格。每次打印一个单词时减少计数。
你的代码将是这样的:
count = remainder_space % space_count;
和输出 block :
i = 0;
while(string[i] != '\0'){
int k = count > 0 ? 1 : 0;
if(string[i] == 0x20){
for(x = 0; x < space_power + k; x++){
printf("%c", 0x20);
}
count--;
}
printf("%c", string[i]);
i++;
}
关于c - 将 % 的值拆分为多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32861356/
我是一名优秀的程序员,十分优秀!