Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops C语言if语句:为更优雅的解决方案编写循环?_Loops - Fatal编程技术网

Loops C语言if语句:为更优雅的解决方案编写循环?

Loops C语言if语句:为更优雅的解决方案编写循环?,loops,Loops,我想知道是否有人能想出一个解决方案来否定使用多个if语句。为了明确我的要求,我们提供了两套代码。第一组代码是工作代码,第二组代码是尝试编写循环,以实现优雅解决方案的目的,即-将工作答案中使用的模式表示为通用算法 #include <stdio.h> #include <string.h> int main() { char str[10] = "copy000000"; int i = 9; int a,b,c; fo

我想知道是否有人能想出一个解决方案来否定使用多个if语句。为了明确我的要求,我们提供了两套代码。第一组代码是工作代码,第二组代码是尝试编写循环,以实现优雅解决方案的目的,即-将工作答案中使用的模式表示为通用算法

#include <stdio.h>
#include <string.h>    

int main()    
{
    char str[10] = "copy000000";
    int i = 9;
    int a,b,c;


    for (a = 0; a < 10; a++)  
    {        

    str[i]++;

    for (b = 0; b < 6; b++)
    {    
    if (str[5] == ':')
        {
        str[5] = '0';
        str[4]++;
        }

    if (str[6] == ':')
        {
        str[6] = '0';
        str[5]++;
        }

    if (str[7] == ':')
        {
        str[7] = '0';
        str[6]++;
        }

    if (str[8] == ':')
        {
        str[8] = '0';
        str[7]++;
        }

    if (str[9] == ':')
        {
        str[9] = '0';
        str[8]++;
        }
     }

    printf("string is: %s\n", str);    
    b = 0;           
    }     

return 0;
}
尝试了概括if循环迭代方式的解决方案:

    for (c = 0; c < 5; c++)
    {
    if (str[d] == ':')
        {
        str[d] = '0';
        str[d-1]++;
        d++;
        }
    }
生成表单的输出:

string is: copy000001
string is: copy000002
string is: copy000003
string is: copy000004
string is: copy000005
string is: copy000006
string is: copy000007
string is: copy000008
string is: copy000009
string is: copy000010
string is: copy000011
string is: copy000012
string is: copy000013
string is: copy000001
string is: copy000002
string is: copy000003
string is: copy000004
string is: copy000005
string is: copy000006
string is: copy000007
string is: copy000008
string is: copy000009
string is: copy00000:
string is: copy00000;
string is: copy00000<
string is: copy00000=

如果您有任何想法,我们将不胜感激。

只需使用b变量创建内部for循环,它应该可以工作:

for(b=9; b > 4; b--){
    if(str[b]==':'){
        str[b] = '0';
        str[b-1]++;
    }
}
您只需将数字从最后一位移到第一位

如果您只需要用于打印,请考虑将数字保持为整数或长,并使用如

中描述的Prtff%d选项打印它。 编辑:缺少分号

您的意思是str[d]='\0';相反您当前的尝试无法9-终止字符串…