c - 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) 的值。
解决方案
如果我选择 (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));
}
推荐阅读
- javascript - 将 https 添加到站点后,我的网页谷歌地图显示空白
- jquery - 单击一次后防止单击,直到用户再次单击另一个按钮
- python - 多边形图
- sql - Presto / Athena:如何在另一列上执行时间序列窗口函数时按一列的分类值分组?
- dataset - 匿名用户发布和共享链接后如何下载 Power BI 报表数据集
- mongodb - nginx背后的mongo图
- javascript - 如何在 Javascript 中设置 CSS 关键帧?
- javascript - 获取状态为 CMM Approved 的 jQuery 数据表的数据
- build - 在 OS RedHat 3.10.0-862.rt56.804.el7.x86_64 中使用 dpdk-setup.sh 构建 DPDK 17.11.5 失败
- django - 带有确认电子邮件的 Django 注册,错误:save() 得到了一个意外的关键字参数 'commit'