首页 > 解决方案 > c中的for循环减法问题

问题描述

#include <stdio.h>
int main() {
int a , b, i , sum = 0 ;
printf("\a");
 printf("\n\t\t What is the number you want to begin"               
        " subtraction with ?   ");
    scanf("%d",&a);
     printf("\n\t\t What is the number you want to end"
            " subtraction with ?   ");
    scanf("%d",&b);
    
      printf("\a");
      printf("\n\t\t The result of the subtraction of numbers from %d to %d :\n"
      , a , b);
      printf("\t\t   ");
      for (i = a ; i >= b+1 ; i--){
        printf("%d - ", i);
        sum = sum - i ;
      printf("%d = %d\n\n", b , sum);
      return 0;
     }

我想创建一个程序,使用 C 编程语言中的 for 循环从 a 减去 a 到 b 的数字序列。我试了很多次,都没有找到解决办法。我想要一个这样运行的程序:例如,如果我选择 (a) 为 8 和 (b) 为 5,我希望程序编写8-7-6-5 = -10. 我想要一个这样运行的程序,具体取决于我在 c 编程中使用 for 循环选择 (a) 和 (b) 的值。

标签: cfor-loopsubtraction

解决方案


如果我选择 (a) 作为 8 和 (b) 作为 5,我希望程序写 8-6-5 = -3

我相信你忘记了数字7,它应该是8-7-6-5 = -10

如果是:

int myfunc(int start, int end)
{
    int result = start;
    for(int index = start - 1; index >= end; index--)
    {
        result -= index;
    }
    return result;
}


int main(void)
{
    printf("%d", myfunc(8,5));
}

https://godbolt.org/z/6133cjbK1

如果要打印整个表达式:


int myfunc(int start, int end)
{
    int result = start;
    printf("%d", start);
    for(int index = start - 1; index >= end; index--)
    {
        printf("-%d", index);
        result -= index;
    }
    return result;
}


int main(void)
{
    printf("=%d", myfunc(8,5));
}

推荐阅读