[英](C) code cant work with all wanted conditions
#include <stdio.h>
#include <stdlib.h>
#define TEN 10
int main ()
{
int number = 0;
int digit = 0;
int last_digit = 0;
int digit_sum = 0;
int i = 0;
while (i == 0)
{
printf("Please Enter A Positive Number! \n"); //explaining
scanf("%d",&number);
if (number > 0)
{
i++;
}
}
while (number > 0)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
if (last_digit != digit) //comparing digits
{
last_digit = digit;
digit_sum += digit;
}
}
printf("The Sum Of The Digits Is : %d",digit_sum);
return 0;
}
該代碼會將數字分為數字,並檢查是否有重復的數字,如果有的話,將僅計算其中一個:3211 3 + 2 + 1,但是我的問題是該代碼無法使用類似數字的代碼31211我感謝您提供的任何幫助。
該代碼不起作用,因為不能保證重復項將連續出現。 您的代碼無法通過其他方式來處理。 這就是為什么它失敗了。
一個簡單的解決方案是考慮使用10個元素的數組,您將在其中記錄出現的元素和未出現的元素。
這個想法是將數字映射到10個元素數組的數組索引。 初始化為0
。
...
int digitAppeared[10]={0};
while (number)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
digit_sum += (1 - digitAppeared[digit]) * digit;
digitAppeared[digit] = 1;
}
...
為了讓您有一個清晰的主意,此行基本上檢查該元素是否出現,並根據結果將添加數字。
如果出現數字D
則digitAppeared[D]=1
;如果沒有出現,則digitAppeared[D]=0
。
如果它是第一次出現,我們會將其添加到digitsum中。 這就是為什么(1-digitAppeared[D])
會告訴我們是否添加它的原因。
digit_sum += (1 - digitAppeared[digit]) * digit;
使用itoa()將數字轉換為字符串。 對其進行排序,然后遍歷,尋找唯一編號並進行計算
您可以通過設置邏輯標志來標記已經添加了哪些數字,如下面程序中的done
所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEN 10
int main ()
{
int number = 0;
int digit = 0;
int last_digit = 0;
int digit_sum = 0;
int i = 0;
int done[10];
while (i == 0)
{
printf("Please Enter A Positive Number! \n"); //explaining
scanf("%d",&number);
if (number > 0)
{
i++;
}
}
memset(done,0,sizeof(done));
while (number > 0)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
if(done[digit] == 0)
{
digit_sum += digit;
done[digit] = 1;
}
}
printf("The Sum Of The Digits Is : %d",digit_sum);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.